用C++在main函数中,先从键盘上输入一个3行3列数组的各个元素的值,然后调用函数fun,其功能是按主对角线进行转置,然后在main函数中输出转置后的数组。
时间: 2023-07-15 13:09:53 浏览: 117
以下是实现代码:
```cpp
#include <iostream>
using namespace std;
void fun(int (*arr)[3], int n) {
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
int temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
}
}
int main() {
int arr[3][3];
cout << "请输入一个3行3列数组的各个元素的值:" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cin >> arr[i][j];
}
}
cout << "转置前的数组:" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
fun(arr, 3);
cout << "转置后的数组:" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
运行结果:
```
请输入一个3行3列数组的各个元素的值:
1 2 3
4 5 6
7 8 9
转置前的数组:
1 2 3
4 5 6
7 8 9
转置后的数组:
1 4 7
2 5 8
3 6 9
```
阅读全文