c语言编写一个函数,使给定的一个二维数组(3×3)转置,即行列互换。
时间: 2024-05-13 10:18:37 浏览: 63
可以使用以下代码实现二维数组转置:
```c
void transpose(int arr[3][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;
}
}
}
```
这个函数接受一个3×3的二维数组作为参数,并对其进行转置操作。具体实现是通过对角线交换实现的。在每次迭代中,我们交换数组中(i,j)和(j,i)位置上的元素。
相关问题
c语言 编写一个函数,使给定的一个二维数组(3×3)转置,即行列互换。
可以按照以下的代码实现:
```c
#include <stdio.h>
void transpose(int arr[3][3]) {
int temp;
for (int i = 0; i < 3; i++) {
for (int j = i; j < 3; j++) {
// 交换 arr[i][j] 和 arr[j][i]
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}};
printf("原始数组:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
transpose(arr);
printf("转置后的数组:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
```
输出结果:
```
原始数组:
1 2 3
4 5 6
7 8 9
转置后的数组:
1 4 7
2 5 8
3 6 9
```
在 `transpose` 函数中,我们使用一个 `temp` 变量来保存交换的值。然后使用两个嵌套的循环来遍历数组,交换每个元素与其对应的行列元素。最后在主函数中调用 `transpose` 函数并输出结果。
用C语言编写一个函数,是给定的一个3×3的二维整型数组转置,即行列互换。
以下是用C语言编写的函数实现3x3二维数组的转置:
```c
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;
}
}
}
```
使用方法:
```c
int main() {
int arr[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}};
printf("Original array:\n");
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
transpose(arr);
printf("\nTransposed array:\n");
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
```
输出结果:
```
Original array:
1 2 3
4 5 6
7 8 9
Transposed array:
1 4 7
2 5 8
3 6 9
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)