c语言实现 矩阵的转置
时间: 2023-11-22 17:46:49 浏览: 174
使用C语言实现矩阵转置.pdf
要在C语言中实现矩阵的转置,可以使用一个临时数组来存储转置后的矩阵。下面是一个示例代码:
```c
#include <stdio.h>
void matrix_transpose(int rows, int cols, int matrix[rows][cols], int transposed[cols][rows]) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transposed[j][i] = matrix[i][j];
}
}
}
int main() {
int matrix[3][4] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}};
int transposed[4][3];
matrix_transpose(3, 4, matrix, transposed);
printf("Original matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
printf("\nTransposed matrix:\n");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", transposed[i][j]);
}
printf("\n");
}
return 0;
}
```
此示例中,我们定义了一个3行4列的矩阵,然后通过 `matrix_transpose` 函数将其转置,并将结果存储在 `transposed` 数组中。最后,我们打印出原始矩阵和转置后的矩阵。
输出结果:
```
Original matrix:
1 2 3 4
5 6 7 8
9 10 11 12
Transposed matrix:
1 5 9
2 6 10
3 7 11
4 8 12
```
这样,我们就成功地实现了矩阵的转置。
阅读全文