编写并测试3×3矩阵转置函数,使用数组保存3×3矩阵。
时间: 2023-06-05 17:09:17 浏览: 93
好的,关于3×3矩阵转置函数的编写,下面是一个示例代码:
```cpp
void transpose_3x3(int matrix[3][3])
{
int temp;
for (int i = 0; i < 3; i++)
{
for (int j = i; j < 3; j++)
{
temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
```
在这里,我们使用一个嵌套的for循环,遍历矩阵中每一个元素,并且通过一个临时变量temp来交换矩阵中对应的元素,从而完成矩阵的转置。测试代码示例如下:
```cpp
#include <iostream>
using namespace std;
void transpose_3x3(int matrix[3][3]);
int main()
{
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
transpose_3x3(matrix);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}
void transpose_3x3(int matrix[3][3])
{
int temp;
for (int i = 0; i < 3; i++)
{
for (int j = i; j < 3; j++)
{
temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
```
输出如下:
```
1 4 7
2 5 8
3 6 9
```
注意,这里我们使用了数组来保存3×3矩阵,而矩阵转置函数的参数也是一个3×3的二维数组。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)