您的位置:首页 > 编程语言 > C语言/C++

C语言程序设计 练习题参考答案 第四章 (2) 二维数组

2008-04-17 16:15 295 查看
/* 4.16 5*5矩阵中每行的绝对值最大值,与同行对角线交换*/

#include "stdio.h"

#include "math.h"
void main()
{
int a[5][5]={{1,2,3,4,-5},{3,5,-2,4,2},{4,1,2,3,-2},
{1,3,-2,4,6},{2,2,0,7,4}} ;
int i,k,max,sub,temp;
/* i 循环变量,控制行, k 循环变量,控制列,max 当前最大绝对值,sub 当前最大绝对值元素的下标
temp 临时用于交换的变量 */

printf("交换之前,输出\n"); /*交换之前,输出*/
for(i=0;i<=4;i++)
{
for(k=0;k<=4;k++)
printf("%4d",a[i][k]);
printf("\n");
}
/*交换*/
for(i=0;i<=4;i++)
{
/*假设第一个元素最大*/
max=fabs(a[i][0]); sub=0;
/*寻找绝对值最大的元素记下下标*/
for(k=1;k<=4;k++)
{
if(fabs(a[i][k])>max)
{
max=fabs(a[i][k]); sub=k;
}
}
/*交换*/
temp=a[i][i]; a[i][i]=a[i][sub]; a[i][sub]=temp;
}
/*交换之后,输出*/
printf("交换之后,输出\n");
for(i=0;i<=4;i++)
{
for(k=0;k<=4;k++)
printf("%4d",a[i][k]);
printf("\n");
}

}

/* 4.17 在一个一维数组中存放任意4个数,如:5,1,8,6,生成如下矩阵
5 5 5 5 5 5 5
5 1 1 1 1 1 5
5 1 8 8 8 1 5
5 1 8 6 8 1 5
5 1 8 8 8 1 5
5 1 1 1 1 1 5
5 5 5 5 5 5 5
*/
#include "stdio.h"
#include "conio.h"
void main()
{
int FourNumbers[4], array[7][7], i , row, column;
printf("请输入4个整数\n");
scanf("%d%d%d%d",&FourNumbers[0],&FourNumbers[1],&FourNumbers[2],&FourNumbers[3]);
for(i=0;i<=3;i++)
{
for(row=i;row<=6-i;row++)
{
for(column=i;column<=6-i;column++)
array[row][column]=FourNumbers[i];
}
}
/* 输出矩阵 */
for(row=0;row<=6;row++)
{
for(column=0;column<=6;column++)
printf("%4d",array[row][column]);
printf("\n");
}
getch();
}
/* 习题4.19 对一行电文加密,每个字母转换为字母表中循环右移的第三个字母, a-d, b-e, ......z-c */

#include "stdio.h"
void main()
{

int c;
while((c=getchar())!='\n')
{
if( (c>='a' && c<='z') || (c>='A' && c<='Z') )
{
c=c+3;
if ((c>'Z' && c<='Z'+3) || c>'z')
c=c-26;

}
putchar(c);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: