c++编写一个函数,将一个3乘3的矩阵转置,并显示运行结果
时间: 2024-02-19 09:58:29 浏览: 82
以下是将一个3乘3的矩阵转置的C++代码:
```c++
#include <iostream>
using namespace std;
void transpose(int arr[][3]) {
int temp;
for (int i = 0; i < 3; i++) {
for (int j = i + 1; j < 3; j++) {
temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
}
}
int main() {
int arr[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
cout << "Original matrix:" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
transpose(arr);
cout << "Transposed matrix:" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
运行结果为:
```
Original matrix:
1 2 3
4 5 6
7 8 9
Transposed matrix:
1 4 7
2 5 8
3 6 9
```
阅读全文