C语言逆置矩阵
时间: 2023-07-24 21:12:59 浏览: 90
要逆置矩阵,可以先将矩阵进行转置,再将每一行的元素逆序排列。以下是一个示例代码:
```c
#include <stdio.h>
void transpose(int mat[][3], int row, int col) {
int temp;
for (int i = 0; i < row; i++) {
for (int j = i+1; j < col; j++) {
temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
}
}
}
void reverse(int mat[][3], int row, int col) {
int temp;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col/2; j++) {
temp = mat[i][j];
mat[i][j] = mat[i][col-j-1];
mat[i][col-j-1] = temp;
}
}
}
void printMatrix(int mat[][3], int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
printf("%d ", mat[i][j]);
}
printf("\n");
}
}
int main() {
int mat[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
printf("Original matrix:\n");
printMatrix(mat, 3, 3);
transpose(mat, 3, 3);
printf("Transposed matrix:\n");
printMatrix(mat, 3, 3);
reverse(mat, 3, 3);
printf("Reversed matrix:\n");
printMatrix(mat, 3, 3);
return 0;
}
```
输出结果为:
```
Original matrix:
1 2 3
4 5 6
7 8 9
Transposed matrix:
1 4 7
2 5 8
3 6 9
Reversed matrix:
7 4 1
8 5 2
9 6 3
```
阅读全文