要實現數組的行列互換,可以使用兩個循環嵌套遍歷數組,將數組的行與列進行交換。
以下是一個示例代碼:
#include <stdio.h>
#define ROWS 3
#define COLS 4
void transpose(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];
}
}
}
void printMatrix(int matrix[ROWS][COLS]) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
printf("\n");
}
int main() {
int matrix[ROWS][COLS] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}};
int transposed[COLS][ROWS];
printf("Original matrix:\n");
printMatrix(matrix);
transpose(matrix, transposed);
printf("Transposed matrix:\n");
printMatrix(transposed);
return 0;
}
運行結果:
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
在示例代碼中,transpose()
函數用于實現數組的行列互換,printMatrix()
函數用于打印數組。在main()
函數中,首先定義了一個原始矩陣matrix
,然后定義了一個用于存儲轉置后矩陣的數組transposed
。接著,調用transpose()
函數將matrix
轉置為transposed
,最后通過調用printMatrix()
函數打印原始矩陣和轉置后的矩陣。