C语言编程:二维数组对角线求和

2024-11-19 15:24:10
推荐回答(3个)
回答1:

#include
#define N 3
int main()
{
int i,j,sum=0;
int a[N][N]; //假设数组为3*3;
printf("please input :\n");
for(i=0;i for(j=0;j scanf("%d",&a[i][j]);
for(i=0;i sum +=a[i][i];
printf("sum=%d\n",sum);
getchar();
return 0;
}

回答2:

#include
#include

typedef int ElemType;
void main()
{
ElemType **arr;
int n,m;
int i,j;
ElemType sum1=0,sum2=0;
printf("请分别输入行数和列数:\n");
scanf("%d%d",&n,&m);
//动态开辟二维数组
arr=(ElemType**)malloc(n*sizeof(ElemType*));
for(i=0;i *(arr+i)=(ElemType*)malloc(m*sizeof(ElemType));
printf("请输入矩阵元素\n");
for(i=0;i for(j=0;j scanf("%d",(*(arr+i)+j));
printf("检查数据\n");
for(i=0;i for(j=0;j printf("%d ",*(*(arr+i)+j));
printf("\n");
}
printf("\n");
for(i=0;i for(j=0;j if(i==j)sum1+=*(*(arr+i)+j);
if(i+j==m-1)sum2+=*(*(arr+i)+j);
}
printf("主对角线和%d与副对角线和%d差为%d\n",sum1,sum2,sum1-sum2);
//销毁动态开辟的二维数组
for(i=0;i free(*(arr+i));
free(arr);

回答3:

#include
#define n 8
void main()
{
int i,j,sum1=0,sum2=0;
pirntf("please input :\n");
for(i=0;i for(j=0;j scanf("%d",&a[i][j]);
for(i=0;i for(j=0;j {
if(i==j)
sum1+=a[i][j];/*主对角线和为sum1,次对角线之和为sum2*/
if(i+j==n-1)
sum2+=a[i][j];
}
printf("sum1=%d\nsum2=%d\n",sum1,sum2);

}