gaussi
1 #include <iostream> 2 #include <cstdio> 3 #include <math.h> 4 #include <time.h> 5 #include <stdlib.h> 6 using namespace std; 7 const int MAXN = 10000; 8 double a[MAXN][MAXN]; 9 double b[MAXN]; 10 double x[MAXN]; 11 int main() 12 { 13 int n=3; 14 double l; 15 int i,number; 16 double sum; 17 srand((unsigned) time(NULL)); 18 printf("a[][]:\n"); 19 for(int i = 0;i<n;i++){ 20 for(int j = 0;j<n;j++){ 21 number = rand() % 11; 22 a[i][j]=(double)(number*1.131121); 23 printf("%f ",a[i][j]); 24 sum+=a[i][j]; 25 } 26 cout << endl; 27 b[i]=sum; 28 sum=0; 29 } 30 ///消元过程 31 for(int k = 0;k<n-1;k++){///消元行 32 for(int i = k+1;i<n;i++){///被消元行 33 l = a[i][k]/a[k][k]; 34 for(int j = k;j<n;j++){ 35 a[i][j]-=l*a[k][j]; 36 } 37 b[i]-=b[k]*l; 38 } 39 } 40 ///回带过程 41 for(int i = n-1;i>=0;i--){ 42 x[i] = b[i]; 43 for(int j = n-1;j>i;j--){ 44 x[i] -= a[i][j]*x[j]; 45 } 46 x[i] /= a[i][i]; 47 } 48 ///高斯消元法输出 49 printf("x[]:(gaussi)\n"); 50 for(int i = 0;i<n;i++){ 51 printf("%.6f ",x[i]); 52 } 53 cout << endl; 54 55 //------------------------- 56 57 double maxs; 58 ///消元过程 59 for(int k = 0;k<n-1;k++){///消元行 60 int cur = k; 61 maxs = fabs(a[k][k]); 62 for(int i = k;i<n;i++)if(maxs<fabs(a[i][k])){maxs = fabs(a[i][k]);cur = i;}///选主元 63 if(cur != k){ 64 double temp; 65 for(int j = k;j<n;j++){ 66 temp = a[k][j]; 67 a[k][j] = a[cur][j]; 68 a[cur][j] = temp; 69 } 70 temp = b[k];b[k] = b[cur];b[cur] = temp; 71 } 72 73 for(int i = k+1;i<n;i++){///被消元行 74 l = a[i][k]/a[k][k]; 75 for(int j = k;j<n;j++){ 76 a[i][j]-=l*a[k][j]; 77 } 78 b[i]-=b[k]*l; 79 } 80 } 81 82 ///回带过程 83 for(int i = n-1;i>=0;i--){ 84 x[i] = b[i]; 85 for(int j = n-1;j>i;j--){ 86 x[i] -= a[i][j]*x[j]; 87 } 88 x[i] /= a[i][i]; 89 } 90 ///高斯列主元素消元法输出 91 printf("x[]:(gaussi_row)\n"); 92 for(int i = 0;i<n;i++){ 93 printf("%.6f ",x[i]); 94 } 95 cout << endl; 96 return 0; 97 }