这是我写的一个用行主元的高斯消去法解方程组的程序,编译已通过了,但不能得到正确答案或者有float point error:domain的错误提示,请各位大虾指导一下.
#define n 4 #include <math.h> void exchrow(double a[n+1][n+1],double b[n+1])/*选主元*/ { double temp,max; int i,j,k,m; for(k=1;k<=n-1;k++) { max=fabs(a[k][k]); for(i=k+1;i<=n;i++) if(fabs(a[i][k]>max)) {max=fabs(a[i][k]); m=i;} if(k!=m) {for(j=1;j<=n;j++) { temp=a[k][j]; a[k][j]=a[m][j]; a[m][j]=temp;} temp=b[m];b[m]=b[k];b[k]=temp;} } } void eliminate(double a[n+1][n+1],double b[n+1])/*消元*/ { int i,j,k; for(k=1;k<=n-1;k++) {for(i=k+1;i<=n;i++) {for(j=k;j<=n;j++) a[i][j]=a[i][j]-a[k][j]*a[i][k]/a[k][k]; b[i]=b[i]-b[k]*a[i][k]/a[k][k]; } } } void backsub(double a[n+1][n+1],double b[n+1])/*回代*/ { int i,j; double sum=0.0; b[n]=b[n]/a[n][n];/*解得的x[i]存放在b[i]中*/ for(i=n-1;i>=1;i--) {for(j=i+1;j<=n;j++) sum+=a[i][j]*b[j]; b[i]=(b[i]-sum)/a[i][i];} } main() {double a[n+1][n+1],b[n+1]; int i,j; printf("input a\n"); for(i=1;i<=n;i++) for(j=1;j<=n;j++) { printf("a[%d][%d]=",i,j); scanf("%f",&a[i][j]);} printf("input b\n"); for(i=1;i<=n;i++) {printf("b[%d]=",i); scanf("%f",&b[i]);} exchrow(a,b); eliminate(a,b); backsub(a,b); printf("root is\n"); for(i=1;i<=n;i++) printf("x[%d]=%f\n",i,b[i]); }