将一个给定的n*n的数字方阵转置,即行列互换C++代码
时间: 2024-02-25 18:53:15 浏览: 83
以下是将一个给定的n*n的数字方阵转置,即行列互换的C++代码:
```c++
#include <iostream>
using namespace std;
int main() {
int n;
cout << "请输入方阵阶数n:";
cin >> n;
int matrix[n][n];
cout << "请输入" << n*n << "个数字,每个数字用空格分隔:" << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
}
}
cout << "原矩阵为:" << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
// 转置矩阵
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
cout << "转置矩阵为:" << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
该程序使用二维数组存储方阵,通过嵌套循环遍历矩阵元素实现转置操作。
阅读全文