编写程序, 实现任意矩阵的转置(即行列互换)使用c语言且需要函数调用
时间: 2024-03-19 16:44:43 浏览: 109
好的,以下是一个实现矩阵转置的 C 语言代码,其中使用了函数调用:
```c
#include <stdio.h>
// 转置函数
void transpose(int mat[][3], int tr[][4], int row, int col) {
int i, j;
for (i = 0; i < col; i++) {
for (j = 0; j < row; j++) {
tr[i][j] = mat[j][i];
}
}
}
// 打印函数
void printMatrix(int mat[][4], int row, int col) {
int i, j;
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
printf("%d ", mat[i][j]);
}
printf("\n");
}
}
int main() {
int mat[3][4] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}};
int tr[4][3];
printf("Original Matrix:\n");
printMatrix(mat, 3, 4);
transpose(mat, tr, 3, 4);
printf("Transposed Matrix:\n");
printMatrix(tr, 4, 3);
return 0;
}
```
代码中的 `transpose` 函数可以接收一个二维数组 `mat`,表示原始矩阵,一个二维数组 `tr`,表示转置后的矩阵,以及矩阵的行数和列数。函数中使用两个循环遍历原始矩阵的每个元素,并将其放入转置矩阵中相应的位置。
`printMatrix` 函数用于打印矩阵,方便我们观察矩阵转置的结果。
在 `main` 函数中,我们定义了一个 3 行 4 列的原始矩阵 `mat`,以及一个 4 行 3 列的转置矩阵 `tr`。首先打印出原始矩阵,然后调用 `transpose` 函数,将原始矩阵转置并存储在 `tr` 中,最后打印出转置矩阵。
你可以根据需要修改矩阵的大小,或者将数组作为函数参数传递到其他函数中。
阅读全文
相关推荐
![](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://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)