TheAlgorithms-C-Plus-Plus/computer_oriented_statistical_methods/Gaussian_elimination.cpp

64 lines
1.5 KiB
C++
Raw Normal View History

2020-04-18 10:43:43 +08:00
#include <iostream>
using namespace std;
int main()
{
2019-08-21 10:10:08 +08:00
int mat_size, i, j, step;
2019-08-21 10:10:08 +08:00
cout << "Matrix size: ";
cin >> mat_size;
2019-08-21 10:10:08 +08:00
double mat[mat_size + 1][mat_size + 1], x[mat_size][mat_size + 1];
2019-08-21 10:10:08 +08:00
cout << endl
<< "Enter value of the matrix: " << endl;
for (i = 0; i < mat_size; i++)
{
2019-08-21 10:10:08 +08:00
for (j = 0; j <= mat_size; j++)
{
2019-08-21 10:10:08 +08:00
cin >> mat[i][j]; //Enter (mat_size*mat_size) value of the matrix.
}
}
2019-08-21 10:10:08 +08:00
for (step = 0; step < mat_size - 1; step++)
{
for (i = step; i < mat_size - 1; i++)
{
2019-08-21 10:10:08 +08:00
double a = (mat[i + 1][step] / mat[step][step]);
2019-08-21 10:10:08 +08:00
for (j = step; j <= mat_size; j++)
mat[i + 1][j] = mat[i + 1][j] - (a * mat[step][j]);
}
}
2019-08-21 10:10:08 +08:00
cout << endl
<< "Matrix using Gaussian Elimination method: " << endl;
for (i = 0; i < mat_size; i++)
{
2019-08-21 10:10:08 +08:00
for (j = 0; j <= mat_size; j++)
{
x[i][j] = mat[i][j];
2019-08-21 10:10:08 +08:00
cout << mat[i][j] << " ";
}
2019-08-21 10:10:08 +08:00
cout << endl;
}
2019-08-21 10:10:08 +08:00
cout << endl
<< "Value of the Gaussian Elimination method: " << endl;
for (i = mat_size - 1; i >= 0; i--)
{
double sum = 0;
2019-08-21 10:10:08 +08:00
for (j = mat_size - 1; j > i; j--)
{
x[i][j] = x[j][j] * x[i][j];
sum = x[i][j] + sum;
}
2019-08-21 10:10:08 +08:00
if (x[i][i] == 0)
x[i][i] = 0;
else
2019-08-21 10:10:08 +08:00
x[i][i] = (x[i][mat_size] - sum) / (x[i][i]);
2019-08-21 10:10:08 +08:00
cout << "x" << i << "= " << x[i][i] << endl;
}
2019-08-21 10:10:08 +08:00
return 0;
}