输入一个M行M列的二维数组,分别计算两条对角线上的元素之和。M由下面的符号常量定义:

#define M 5
2024-11-22 15:35:21
推荐回答(5个)
回答1:

#include
#define M 5
void main()
{
int a[M][M],i,j,sum1=0,sum2=0;
printf("输入数组:\n");
for(i=0;i {
for(j=0;j {
printf("a[%d][%d]= ",i,j);
scanf("%d",&a[i][j]);
}
}
for(i=0;i {
sum1+=a[i][i];
sum2+=a[i][M-i];
}
printf("sum1= %d\n",sum1);
printf("sum2= %d\n",sum2);
}

回答2:

#include

void main()
{
int array[M][M];
int sum;
int i,j;

printf("请输入数组的各个数值");
for (i=0; ifor (j=0; jscanf("%d",&array[i][j]);

sum = 0;
for (i=0; isum += array[i][i] + array[i][M-i-1];

if (M%2 == 1)
sum -= array[M/2][M/2];

printf("对角线之和为:%d\n",sum);
}

回答3:

#include
#define M 5
main()
{
int a[M][M],i,j,sum1=0,sum2=0;
printf("请输入M*M=%d个数",M*M);
for(i=0;ifor(j=0;jscanf("%d",&a[i][j]);

for(i=0;i{
sum1+=a[i][i];
sum2+=a[i][M-i];
}
printf("\n\n两条对角线的和sum1=%d\nsum2=%d",sum1,sum2);
}

回答4:

#define M 5
main()
{
int a[5][5],i,j,s1=0,s2=0;
for (i=0;i<5;i++)
for (j=0;j<5;j++)
scanf ("%d",&a[i][j]);
for(i=0;i<5;i++)
{for (j=0;j<5;j++)
if(i==j) s1+=a[i][j];}
printf ("%d\n",s1);
for(i=0,j=4;i<5,j>=0;i++,j--)
s2+=a[i][j];
printf("%d\n",s2);
}

回答5:

int sum1=0,sum2=0;
for(int i=0;i<5;i++)
{
sum1+=a[i][i];
sum2+=a[i][4-i];
}