求一个3×3矩阵对角线元素之和
int main()
{
vector<vector<int>> vec;
int row, col;
int Maindiagonal = 0;
int Subdiagonal = 0;
cout << "请输入行、列的值(行列值相等):";
cin >> row >> col;
vec.resize(row);
for (int i = 0; i < row; i++)
{
vec[i].resize(col);
}
for (int i = 0; i < row; i++)
{
cout << "请输入第" << i << "行的值:";
for (int j = 0; j < col; j++)
{
int num;
cin >> num;
vec[i][j] = num;
}
}
cout << "矩阵为:" << endl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
cout << setw(5) << vec[i][j];
if (i == j)
{
Maindiagonal += vec[i][j];
}
if (i + j + 1 == row)
{
Subdiagonal += vec[i][j];
}
}
cout << endl;
}
cout << "主对角线之和为:" << Maindiagonal << endl;
cout << "副对角线之和为:" << Subdiagonal << endl;
return 0;
}