C++编写程序。(1)初始化一个矩阵A(5×5),元素值取自随机函数,并输出;(2)将其传递给函数,实现矩阵转置;(3)在主函数中输出结果。
时间: 2024-05-16 15:13:49 浏览: 93
以下是C++代码实现:
```cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void transpose(int A[][5], int n)
{
for (int i = 0; i < n; ++i)
{
for (int j = i; j < n; ++j)
{
int temp = A[i][j];
A[i][j] = A[j][i];
A[j][i] = temp;
}
}
}
int main()
{
srand(time(NULL)); // 设置随机数种子
int A[5][5];
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 5; ++j)
{
A[i][j] = rand() % 100 + 1; // 生成1-100的随机数
cout << A[i][j] << " ";
}
cout << endl;
}
transpose(A, 5); // 调用矩阵转置函数
cout << "After transpose:" << endl;
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 5; ++j)
{
cout << A[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
运行结果示例:
```
60 98 30 94 36
77 16 84 22 32
21 7 14 88 71
94 84 71 57 64
45 49 54 45 89
After transpose:
60 77 21 94 45
98 16 7 84 49
30 84 14 71 54
94 22 88 57 45
36 32 71 64 89
```
阅读全文