只有行列相等的矩阵即方阵才有主、副对角线,其格式如下:
如图,
计算主对角线元素之和即计算:
计算副对角线元素之和即计算:
#include "stdio.h" #define N 3 int main(void) { int i = 0, j = 0; int main_sum = 0, sub_sum = 0; int matrix[N][N] = {0}; //输入数组 for (i = 0; i < N; i++) { printf("请输入第%d行元素:\n", i+1); for (j = 0; j < N; j++) scanf_s("%d", &matrix[i][j]); } //计算主对角线元素之和 for (i = 0, j = 0; i < N; i++, j++) main_sum += matrix[i][j]; //计算副对角线元素之和 for (i = 0, j = N - 1; i < N; i++, j--) sub_sum += matrix[i][j]; //输出主副对角线元素的和 printf("矩阵主对角线元素之和为:%d\n", main_sum); printf("矩阵副对角线元素之和为:%d\n", sub_sum); return 0; }