前言
二级刷题,做到有意思的题目,仅做个记录,有更好的想法可以一起探讨一下,我个人代码能力不足勿喷。
一、题目解析
逆置矩阵,即将第一列元素放到第一行上,第二列元素放到第二行上,依次类推。
动手画一下即可知道,假设i表示列,j表示行,array代表矩阵,逆置矩阵时,正对角线元素(即i=j的元素)是不需要变位置的,以该元素为
起点,分别将其行列后面的元素对应互换,也即是将array[i][j] 与array[j][i]互换即可,
二、个人代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 5
void MatrixPrint(int (*)[N]);
void MatrixInverse(int (*)[N]);
int main(int argc, char const *argv[])
{
int i, j, x;
int matrix[N][N];
time_t t;
srand(time(&t));
for(i=0; i<N; i++)
for(j=0; j<N; j++)
{
x =rand() % 100;
matrix[i][j] = x;
}
printf("Original matrix:\n");
MatrixPrint(matrix);
MatrixInverse(matrix);
printf("\nInverse matrix:\n");
MatrixPrint(matrix);
return 0;
}
void MatrixPrint(int (*pMatrix)[N])
{
for(int i=0; i<N; i++)
{
for(int j=0; j<N;j++)
printf("%d ", pMatrix[i][j]);
printf("\n");
}
}
void MatrixInverse(int (*pMatrix)[N])
{
int temp;
for(int i=0; i<N; i++)
for(int j=i+1; j<N; j++)
{
temp = pMatrix[i][j];
pMatrix[i][j] = pMatrix[j][i];
pMatrix[j][i] = temp;
}
}
运行输出
Original matrix:
52 67 91 35 6
7 73 8 78 49
3 91 74 57 59
43 7 66 87 22
58 84 7 52 19
Inverse matrix:
52 7 3 43 58
67 73 91 7 84
91 8 74 66 7
35 78 57 87 52
6 49 59 22 19