要實現(xiàn)數(shù)組的行列互換,可以使用兩個循環(huán)嵌套遍歷數(shù)組,將數(shù)組的行與列進(jìn)行交換。
以下是一個示例代碼:
#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;
}
運行結(jié)果:
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()
函數(shù)用于實現(xiàn)數(shù)組的行列互換,printMatrix()
函數(shù)用于打印數(shù)組。在main()
函數(shù)中,首先定義了一個原始矩陣matrix
,然后定義了一個用于存儲轉(zhuǎn)置后矩陣的數(shù)組transposed
。接著,調(diào)用transpose()
函數(shù)將matrix
轉(zhuǎn)置為transposed
,最后通過調(diào)用printMatrix()
函數(shù)打印原始矩陣和轉(zhuǎn)置后的矩陣。