用c语言分别写出n阶方阵a的主对角线元素和,副对角线元素之和,非对角线元素之和
时间: 2024-01-08 09:50:35 浏览: 68
下面是用 C 语言实现的代码:
```c
#include <stdio.h>
int main()
{
int a[10][10], i, j, n, sum1 = 0, sum2 = 0, sum3 = 0;
printf("Enter the order of matrix: ");
scanf("%d", &n);
printf("Enter the elements of matrix:\n");
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
scanf("%d", &a[i][j]);
}
}
// 计算主对角线元素之和
for(i = 0; i < n; i++)
{
sum1 += a[i][i];
}
// 计算副对角线元素之和
for(i = 0, j = n - 1; i < n && j >= 0; i++, j--)
{
sum2 += a[i][j];
}
// 计算非对角线元素之和
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
if(i != j && i + j != n - 1)
{
sum3 += a[i][j];
}
}
}
printf("Sum of main diagonal elements: %d\n", sum1);
printf("Sum of secondary diagonal elements: %d\n", sum2);
printf("Sum of non-diagonal elements: %d\n", sum3);
return 0;
}
```
假设输入的方阵为:
```
1 2 3
4 5 6
7 8 9
```
则输出结果为:
```
Enter the order of matrix: 3
Enter the elements of matrix:
1 2 3
4 5 6
7 8 9
Sum of main diagonal elements: 15
Sum of secondary diagonal elements: 15
Sum of non-diagonal elements: 28
```
阅读全文