Hello
Help to correct the program, defines roots correctly, but in a wrong order
My answer: 0.63, -0.12, 0.0249, 1.16, -0.49, -0.0558Code:#include <iostream> #include <cmath> using namespace std; void Gauss(double *a, double *b, double *x,int n) { int i,j,k,t; double kof,s; double temp; for (i=n-1; i>0; --i) { for (t=i, j=i-1; j>=0; --j) { if (fabs(a[i*n+t])<fabs(a[i*n+j])) { t=j; } } if (a[i*n+t]==0.0) { return; } if (t!=i) { for (k=n-1; k>=0; --k) { temp=a[k*n+t]; a[k*n+t]=a[k*n+i]; a[k*n+i]=temp; } } for (j=i-1; j>=0; --j) { kof=a[i+j*n]/a[i*n+i]; // kof=a[j][i]/a[i][i]; for (a[i+j*n]=0.0, b[j]-=b[i]*kof, k=i-1; k>=0; --k) { a[k+j*n]-=a[k+i*n]*kof; // a[k][j]-=a[k][i]*kof } } } x=new double [n]; if (x) { for (i=0; i<n; ++i) { for (s=0.0, j=i-1; j>=0; --j) { s+=a[j+i*n]*x[j]; //s+=a[j][i]*x[j] } x[i]=(b[i]-s)/a[i*n+i]; // x[i]=(b[i]-s)/a[i][i]; //cout << x[i] << "\n"; } } cout << "\n"; for (i=0; i<n; ++i) cout << "x " << x[i] << endl; } main() { int n = 6; double gauss2[6] ={1,5,3,7,6,3}; double M[36]={-3, 2, 1,2, 3, 1,5, 3, 3, -1, 3, 4,0, 80,46, 34, 3, 4,6, 7, 3, 6, 6,7,57, 6, 5, 5, 3, 67,1, 55, 5, 7, 3, 7 }; double *y = new double[n]; /* for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { //cin >> M[i+j*n]; M[i+j*n] = rand()/100; //cout << "gauss1["<< i << "][" << j << "]="; //cin >> gauss1[i][j]; } } */ for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { cout << M[i*n+j] << " "; } cout << gauss2[i] << endl; } Gauss(M,gauss2,y,n); cin.get(); }
Right answer: 0.63, 0.06, 0.02, -0.12, 1.16, -0.49
Why not just sort your array before outputting it? Gauss's method is not guaranteed to generate roots in any particular order.
If Substituting: 0.63, -0.12, 0.0249, 1.16, -0.49, -0.0558 , then the right decision not succeed
so that the sequence of roots is important
Again, why not just sort the array before printing it?
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks