m.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
ifstream in("in.txt");
string s;
getline(in, s);
// read for length
int length;
{
istringstream sin(s);
sin >> length;
}
// dim array
double** arr = new double*[length];
for (int i = 0; i < length + 1; ++i)
arr[i] = new double[length + 1];
for (int i = 0; i < length && getline(in, s); ++i)
{
istringstream sin(s);
for (int j = 0; j < length + 1; ++j)
sin >> arr[i][j];
}
double tmp;
// before
cout << "before:" << endl;
for (int i=0; i<length; ++i)
{
for (int j=0; j<length+1; ++j)
cout << arr[i][j] << " ";
cout << endl;
}
// 1st step
for (int i=1; i<length; ++i)
{
for (int j=i; j<length; ++j)
{
tmp = 1.0 * arr[j][i-1] / arr[i-1][i-1];
for (int k=i; k<length+1; ++k)
arr[j][k] -= 1.0 * tmp * arr[i-1][k];
}
}
cout << "after:" << endl;
for (int i=0; i<length; ++i)
{
for (int j=0; j<length+1; ++j)
cout << arr[i][j] << " ";
cout << endl;
}
// 2nd step
for (int i=length-1; i>=0; --i)
{
tmp = 0.0;
for (int j=length-1; j>i; --j)
tmp += arr[i][j] * arr[j][length];
arr[i][length] = 1.0 * (arr[i][length] - tmp) / arr[i][i];
}
cout << "result:" << endl;
for (int i=0; i<length; ++i)
cout << arr[i][length] << endl;
return 0;
}
in.txt
3
12 2 -6 7
2 4 -6 -1
-6 -6 24 6
output
before:
12 2 -6 7
2 4 -6 -1
-6 -6 24 6
after:
12 2 -6 7
2 3.66667 -5 -2.16667
-6 -5 14.1818 6.54545
result:
0.807692
0.0384615
0.461538