c++编一个函数将3×3的矩阵转置
时间: 2023-07-15 20:13:26 浏览: 46
可以使用以下代码实现:
```c++
void transpose(int matrix[3][3]) {
for (int i = 0; i < 3; i++) {
for (int j = i + 1; j < 3; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
```
这个函数接受一个3x3的矩阵作为参数,并将其转置。它使用两个嵌套的循环来遍历矩阵,并交换每个元素的行和列索引。注意,在内部循环中,我们只遍历第i+1行到第3行的元素,因为对角线上的元素已经被处理过了(它们不需要被交换)。
相关问题
c++3x3矩阵转置函数
以下是一个C++实现3x3矩阵转置的函数示例:
```c++
#include <iostream>
using namespace std;
void transpose(int arr[3][3]) {
for(int i=0; i<3; i++) {
for(int j=i+1; j<3; j++) {
int 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;
}
```
c++写一函数,将一个3*3的整形矩阵转置
可以使用C++编写一个函数,将一个3*3的整形矩阵转置。
函数代码如下:
```c++
void transpose(int matrix[3][3])
{
for (int i = 0; i < 3; i++)
{
for (int j = i+1; j < 3; j++)
{
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
```
使用该函数,可以将一个3*3的整形矩阵转置。例如,假设有以下矩阵:
```c++
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
}
```
调用该函数
```c++
transpose(matrix);
```
转置后的结果为:
```c++
{
{1, 4, 7},
{2, 5, 8},
{3, 6, 9}
}
```
相关推荐
![](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)