求5列5行矩阵的主副对角线元素之和给出c++代码
时间: 2023-08-31 08:36:31 浏览: 77
以下是求5x5矩阵主副对角线元素之和的C++代码:
```c++
#include <iostream>
using namespace std;
int main() {
int matrix[5][5] = {{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20},
{21, 22, 23, 24, 25}};
int sum_main_diagonal = 0;
int sum_secondary_diagonal = 0;
for (int i = 0; i < 5; i++) {
sum_main_diagonal += matrix[i][i];
sum_secondary_diagonal += matrix[i][4-i];
}
cout << "Sum of main diagonal elements: " << sum_main_diagonal << endl;
cout << "Sum of secondary diagonal elements: " << sum_secondary_diagonal << endl;
return 0;
}
```
注意:以上代码中的矩阵元素是手动输入的,你可以根据需要修改矩阵元素。
阅读全文