I am writing an algorithm to do Gaussian elimination. I do not know why the elements of the matrix do not change after the calculations. I think I might need to defined the elements in a different way, but I do not know how. Is there any other easy way to fix this problem?
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n, i, j, k;
float mult;
cout << "Enter the number of equations\n";
cin >> n;
int a[n][n], x[n], b[n];
for (i=0;i<n;i++)
{
for (int j=0;j<n;j++)
{
cout << "A[" << i+1 << "][" << j+1 << "]=";
cin >> a[i][j];
}
}
for (i = 0; i<n; i++)
{
cout << "b[" << i+1 << "] is ";
cin >> a[i][n];
}
for (j = 0; j< n; j++)
for (i=j+1; i< n ; i++)
mult = a[i][j] / a[j][j];
for (k = j+1; k < n ; k++)
a[i][k] = a[i][k] - mult * a[j][k];
x[n-1] = a[n-1][n]/ a[n-1][n-1];
for (i = n-2; i=0; i--)
for (j=n-1; j = i+1; j--)
a[i][n] = a[i][n] - a[i][j]*x[j];
x[i] = a[i][n] / a[i][i];
}
I see several problems with your code:
In standard c++ int a[n][n], x[n], b[n];
is not valid, because n
is not constant at compile time. Even if some compilers allow this, don't use it. Use std::vector instead.
You should use an IDE or simple Editor to fix intendation for you, then you would see, that the last line x[i] = a[i][n] / a[i][i];
is not part of any loop. My tip: always use parantheses after for
!
The condition of the last loop for(i = n-2; i=0; i--)
is i=0
. This will_assign_ the value 0 to i
then evaluate i
as condition and since i
is zero it will exit the loop. Probably you meant to use ==
to compare the values.
The same thing goes for the nested loop for (j=n-1; j = i+1; j--)
.2
n != 0
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments