1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
|
using namespace std;
void GaussianElimination(double **,double *b ,double *y);
int main(int argc, char * argv[])
{
/* values
Row0 = 0, 2, 1; b0= -8
Row1 = 1, -2, -3; b1 = 0
Row3 = -1, 1, 2; b2= 3
Ans = -4, -5, 2 */
//int **A = new {{0.0, 2.0, 1.0, -8.0}, {1.0, -2.0, -3.0, 0.0},{-1.0, 1.0, 2.0,3.0}};
double *A[n]={NULL, NULL, NULL} ;
double *b = NULL;
double *y= NULL;
for (int i=0; i < n; i++){
A[i] = new double [n];
if (A[i] == NULL){
cout<< " problem with memory Allocation:";
return -2;
}
}
b = new double[n];
if(b== NULL){
cout<< " Null pointer assignment:";
return -2;
}
y = new double[n];
if(y== NULL){
cout<< " Null pointer assignment:";
return -2;
}
A[0][0] =0.0;A[0][1] =2.0; A[0][2] = 1.0; //A[0][3] = -8.0;
A[1][0] =1.0;A[1][1] =-2.0; A[1][2] =-3.0; //A[1][3] = 0.0;
A[2][0] =-1.0;A[0][1] =1.0; A[0][2] = 2.0; //A[0][3] = 3.0;
b[0] = -8.0;
b[1] = 0.0;
b[2] = 3.0;
GaussianElimination(A, b ,y);
delete [] y;
delete [ ]b;
for(int i = 0; i < n; i++)
delete [] A[i];
// delete [ ] A; No need to delete A because A is not created dynamically
}
void GaussianElimination(double **A, double *b,double *y) {
for(int k=0; k<n-1; ++k) {
for(int j= k+1; j <n-1; ++j)
A[k][j] = A[k][j]/A[k][k];
y[k] = b[k]/A[k][k];
for(int i=k+1; k<n-1; i++){
for(int j=k+1; j<n-1; j++)
A[i][j] = A[i][j] -A[i][k] *A[k][j];
b[i]= b[i] -A[i][k] * y[k];
A[i][k] = 0;
}
}
for(int i=0; i<n-1; i++)
cout<<y[i];
}
|