用C语言编写函数void fun(int array[3][3]),实现矩阵(3行3列)的转置(即行列互换)
时间: 2023-06-14 11:08:28 浏览: 86
以下是用 C 语言编写的实现矩阵转置的函数:
```c
void fun(int array[3][3]) {
int temp;
for (int i = 0; i < 3; i++) {
for (int j = i + 1; j < 3; j++) {
temp = array[i][j];
array[i][j] = array[j][i];
array[j][i] = temp;
}
}
}
```
在这个函数中,我们使用两个嵌套的循环来遍历矩阵的所有元素,并将每个元素的值与其对应的行和列进行交换。具体来说,我们通过循环变量 `i` 和 `j` 分别表示矩阵的行和列,然后使用一个临时变量 `temp` 来暂存当前行列的元素值。接着,我们将该元素的值与其对应的行和列进行交换,即将 `array[i][j]` 的值赋给 `array[j][i]`,将 `array[j][i]` 的值赋给 `array[i][j]`。通过这种方式,我们就可以实现矩阵的转置。
相关问题
编写c语言程序, 实现矩阵(3行3列)的转置(即行列互换)
以下是C语言程序实现矩阵(3行3列)的转置:
```c
#include <stdio.h>
int main() {
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // 定义一个3行3列的矩阵
printf("原矩阵:\n");
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
// 矩阵转置
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;
}
}
printf("转置后的矩阵:\n");
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
```
运行结果为:
```
原矩阵:
1 2 3
4 5 6
7 8 9
转置后的矩阵:
1 4 7
2 5 8
3 6 9
```
请编写c语言程序,实现矩阵(3行3列)的转置(即行列互换)
好的,这里是一个实现矩阵转置的C语言程序:
```c
#include <stdio.h>
#define N 3 // 矩阵的行数和列数
void transpose(int matrix[N][N]) {
int tmp;
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
}
int main() {
int matrix[N][N] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
printf("原矩阵:\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
transpose(matrix);
printf("转置后的矩阵:\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
```
程序中定义了一个 `N` 行 `N` 列的矩阵,使用嵌套循环输出原矩阵,然后调用 `transpose` 函数将矩阵进行转置,最后输出转置后的矩阵。转置函数中使用了两个嵌套循环,将矩阵的上三角元素和下三角元素交换位置,完成矩阵的转置。
运行结果:
```
原矩阵:
1 2 3
4 5 6
7 8 9
转置后的矩阵:
1 4 7
2 5 8
3 6 9
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)