#include <iostream> #include <vector> int main() { int n, x; std::cin >> n >> x; std::vector<std::vector<int>> matrix(n, std::vector<int>(n)); // 读取矩阵元素 for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { std::cin >> matrix[i][j]; } } // 更新主对角线元素 for (int i = 0; i < n; i++) { matrix[i][i] += x; } // 更新次对角线元素 for (int i = 0; i < n; i++) { matrix[i][n - 1 - i] += x; } // 输出矩阵 for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { std::cout << matrix[i][j] << " "; } std::cout << std::endl; } return 0; } 把这段代码改成用二维数组实现
时间: 2024-04-15 11:31:12 浏览: 105
动态开辟二维数组.doc )
Certainly! Here's the modified code using a two-dimensional array:
```cpp
#include <iostream>
int main() {
int n, x;
std::cin >> n >> x;
int matrix[n][n];
// 读取矩阵元素
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
std::cin >> matrix[i][j];
}
}
// 更新主对角线元素
for (int i = 0; i < n; i++) {
matrix[i][i] += x;
}
// 更新次对角线元素
for (int i = 0; i < n; i++) {
matrix[i][n - 1 - i] += x;
}
// 输出矩阵
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
```
Please note that in this modified version, a two-dimensional array `matrix` is used instead of a vector.
阅读全文