编辑一个矩阵转置的函数,矩阵的行列数由用户输入
时间: 2023-06-08 12:03:48 浏览: 83
Python 使用Numpy对矩阵进行转置的方法
没问题,我可以帮您编写一个矩阵转置的函数,以下是 C++ 的代码示例:
```c++
#include <iostream>
using namespace std;
int main() {
int n, m;
cout << "请输入矩阵的行数和列数:" << endl;
cin >> n >> m;
int matrix[n][m];
cout << "请输入矩阵元素:" << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> matrix[i][j];
}
}
int transpose[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
transpose[i][j] = matrix[j][i];
}
}
cout << "转置后的矩阵为:" << endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cout << transpose[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
您可以根据需要修改代码,如需要将其封装成函数可以参考以下代码:
```c++
#include <iostream>
using namespace std;
void matrixTranspose(int matrix[][10], int row, int col) {
int transpose[col][row];
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
transpose[i][j] = matrix[j][i];
}
}
cout << "转置后的矩阵为:" << endl;
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
cout << transpose[i][j] << " ";
}
cout << endl;
}
}
int main() {
int matrix[10][10];
int row, col;
cout << "请输入行数和列数:" << endl;
cin >> row >> col;
cout << "请输入矩阵元素:" << endl;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
cin >> matrix[i][j];
}
}
matrixTranspose(matrix, row, col);
return 0;
}
```
阅读全文