Description
给定一个n*n的矩阵,输出它的行列式值和逆矩阵。
Input
第一行一个整数表示n(n < 10),接下来有n行,每行有n个整数。其中第i行第j列用ai,j表示(-100 < ai,j < 100),保证存在逆矩阵
Output
第一行表示行列式值,接下来有n行,每行有n个数(注意可能不是整数,保留两位小数)表示逆矩阵。其中每两个数之间用一个空格隔开,行末不要有多余空格。详情见输出样例。
Sample Input
3
1 -3 7
2 4 -3
-3 7 2
Sample Output
196.00
0.15 0.28 -0.10
0.03 0.12 0.09
0.13 0.01 0.05
我的代码:
1#include <stdio.h>
2
3#define eps 0.00001
4#define iszero(x) ( (-eps<(x)) && ((x)<eps) )
5
6#define L 15
7
8void gauss( double a[ L ][ L ], double x[ L ], double b[ L ], int n ) {
9 int i, j, k;
10 double s;
11 for ( k = 1; k <= n; ++k ) {
12 for ( i = k; (i<=n) && (iszero(a[i][k])); ++i ) {
13 }
14 if ( k != i ) {
15 for ( j = k; j <= n; ++k ) {
16 s = a[ k ][ j ];
17 a[ k ][ j ] = a[ i ][ j ];
18 a[ i ][ j ] = s;
19 }
20 s = b[ k ];
21 b[ k ] = b[ i ];
22 b[ i ] = s;
23 }
24 for ( i = k + 1; i <= n; ++i ) {
25 s = a[ i ][ k ] / a[ k ][ k ];
26 for ( j = k; j <= n; ++j ) {
27 a[ i ][ j ] -= a[ k ][ j ] * s;
28 }
29 b[ i ] -= b[ k ] * s;
30 }
31 }
32 for ( i = n; i >= 1; --i ) {
33 s = b[ i ];
34 for ( j = i + 1; j <= n; ++j ) {
35 s -= x[ j ] * a[ i ][ j ];
36 }
37 x[ i ] = s / a[ i ][ i ];
38 if ( iszero(x[i]) ) {
39 x[ i ] = 0;
40 }
41 }
42}
43
44int main() {
45 double a[ L ][ L ], x[ L ], b[ L ], at[ L ][ L ], ak[ L ][ L ], det;
46 int n, i, j, k;
47 scanf( "%d", &n );
48 for ( i = 1; i <= n; ++i ) {
49 for ( j = 1; j <= n; ++j ) {
50 scanf( "%lf", &ak[ i ][ j ] );
51 }
52 }
53
54 // det
55 for ( i = 1; i <= n; ++i ) {
56 for ( j = 1; j <= n; ++j ) {
57 a[ i ][ j ] = ak[ i ][ j ];
58 }
59 b[ i ] = 0;
60 }
61 gauss( a, x, b, n );
62 det = 1;
63 for ( i = 1; i <= n; ++i ) {
64 det *= a[ i ][ i ];
65 }
66 if ( iszero(det) ) {
67 det = 0;
68 }
69 printf( "%0.2lf\n", det );
70
71 // at
72 for ( k = 1; k <= n; ++k ) {
73 for ( i = 1; i <= n; ++i ) {
74 for ( j = 1; j <= n; ++j ) {
75 a[ i ][ j ] = ak[ i ][ j ];
76 }
77 b[ i ] = 0;
78 }
79 b[ k ] = 1;
80 gauss( a, x, b, n );
81 for ( i = 1; i <= n; ++i ) {
82 at[ i ][ k ] = x[ i ];
83 }
84 }
85 for ( i = 1; i <= n; ++i ) {
86 for ( j = 1; j < n; ++j ) {
87 printf( "%0.2lf ", at[ i ][ j ] );
88 }
89 printf( "%0.2lf\n", at[ i ][ n ] );
90 }
91 return 0;
92}