#include <iostream> #include <cstdio> #include <cmath> #include <algorithm> using namespace std; const int MAXN=105; #define eps 1e-10 double a[MAXN][MAXN],b[MAXN]; int gauss_elimination(int n,double a[][MAXN],double b[]) { int i,j,k,row;double maxs,times; for(k=1 ; k<=n ; k++){ for(maxs=0, i=k; i<=n; i++) if(fabs(a[i][k])>fabs(maxs)) maxs=a[row=i][k]; if(fabs(maxs)<eps) return 0; if(row!=k){ for(j=k; j<=n ; j++) swap(a[k][j],a[row][j]); swap(b[k],b[row]); } for(j=k+1 ; j<=n ; j++){ for(a[k][j]/=maxs, i=k+1 ; i<=n ; i++) a[i][j]-=a[i][k]*a[k][j]; } for(b[k]/=maxs,i=k+1 ; i<=n; i++) b[i]-=b[k]*a[i][k]; } for(int i=n;i>=1; i--) for(j=i+1; j<=n;j++) b[i]-=a[i][j]*b[j]; return 1; } int main() { int n=1; while(n){ cout<<"请输入未知元素个数,n=0取消"<<endl; cin>>n;if(n==0)break; cout<<"请输入加上常数的增广矩阵"<<endl; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++){ scanf("%lf",&a[i][j]); if(j==n) scanf("%lf",&b[i]); } cout<<"has answer as :"<<gauss_elimination(n,a,b)<<endl; for(int i=1;i<=n;i++) printf("%dth = %lf\n",i,b[i]); } return 0; }
|