从键盘输入一个M×M的矩阵,分别求该矩阵主对角线上的元素之和、以及副对角线上的元素之和。要求M的值从键盘输入,且M的值小于10。
时间: 2024-02-11 22:08:27 浏览: 30
好的,这是一个关于矩阵求和的问题,我可以帮你解决。以下是一个简单的 C++ 代码示例:
```c++
#include <iostream>
using namespace std;
int main()
{
int M;
cout << "请输入M的值(M < 10):";
cin >> M;
int matrix[M][M];
int main_sum = 0, sub_sum = 0;
// 输入矩阵
cout << "请输入" << M << "×" << M << "的矩阵:\n";
for (int i = 0; i < M; i++)
{
for (int j = 0; j < M; j++)
{
cin >> matrix[i][j];
if (i == j)
main_sum += matrix[i][j]; // 主对角线
if (i + j == M - 1)
sub_sum += matrix[i][j]; // 副对角线
}
}
// 输出结果
cout << "主对角线上的元素之和为:" << main_sum << endl;
cout << "副对角线上的元素之和为:" << sub_sum << endl;
return 0;
}
```
代码中,我们通过嵌套循环输入矩阵,并在循环中判断当前元素是否在主对角线或副对角线上,如果是,则将其加到对应的和变量中。最后输出两个和变量的值即可。
注意,为了避免数组越界,我们在定义矩阵时使用了变量 M,而不是具体的数字。同时,为了方便输入,我们在输入数字时没有加入太多的错误处理,建议在实际使用时加入更多的验证。
阅读全文
相关推荐














