Description
应用高斯消元法求解n*n的线性方程组Ax=b,其中A为系数矩阵。
数据保证有唯一解。
Input
第1行为一个整数n(0<n<=20),表示是n*n的的线性方程组。
接下去的n行表示了系数矩阵A,每行有n个整数。
再接下去的n行表示了b,每行只有一个整数。
Output
输出有n行,每行有1个小数(精确到0.01),表示方程组的解。
Sample Input
3
1 2 3
2 4 5
3 1 2
4
3
1
Sample Output
-1.40
-4.80
5.00
我的代码:
1
#include <stdio.h>
2
3
#define L 30
4
#define eps 0.00001
5
#define iszero(x) ( ( -eps < x ) && ( x < eps ) )
6
7![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
int gauss( double a[][ L ], double b[], int n, double x[] )
{
8
int i, j, k;
9
double tmp, s, t;
10![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
for ( k = 0; k < n; ++k )
{
11
for ( i = k; ( i < n ) && ( iszero( a[ i ][ k ] ) ); ++i )
12
;
13
if ( i >= n )
14
return 0; // -----
15![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
if ( i != k )
{
16![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
for ( j = k; j < n; ++j )
{
17
tmp = a[ k ][ j ];
18
a[ k ][ j ] = a[ i ][ j ];
19
a[ i ][ j ] = tmp;
20
}
21
tmp = b[ k ];
22
b[ k ] = b[ i ];
23
b[ i ] = tmp;
24
}
25
s = a[ k ][ k ];
26![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
for ( i = k + 1; i < n; ++i )
{
27
t = a[ i ][ k ];
28![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
for ( j = k; j < n; ++j )
{
29
a[ i ][ j ] = a[ i ][ j ] * s - a[ k ][ j ] * t;
30
}
31
b[ i ] = b[ i ] * s - b[ k ] * t;
32
}
33
}
34
x[ n - 1 ] = b[ n - 1 ] / a[ n - 1 ][ n - 1 ];
35![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
for ( i = n - 2; i >= 0; --i )
{
36
x[ i ] = b[ i ];
37![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
for ( j = i + 1; j < n; ++j )
{
38
x[ i ] -= x[ j ] * a[ i ][ j ];
39
}
40
x[ i ] /= a[ i ][ i ];
41
}
42
return 1;
43
}
44
45![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
int main()
{
46
double a[ L ][ L ], b[ L ];
47
double x[ L ];
48
int i, j, n;
49![](http://www.cppblog.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
while ( scanf( "%d", &n ) != EOF )
{
50
for ( i = 0; i < n; ++i )
51
for ( j = 0; j < n; ++j )
52
scanf( "%lf", &a[ i ][ j ] );
53
for ( i = 0; i < n; ++i )
54
scanf( "%lf", &b[ i ] );
55
gauss( a, b, n, x );
56
for ( i = 0; i < n; ++i )
57
printf( "%0.2lf\n", x[ i ] );
58
}
59
return 0;
60
}