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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
|
#include<iostream>
#include<cmath>
#include<fstream>
using namespace std;
ofstream fout ("output matrix gauss.txt");
double matrix[1000][1000];
//class for a position variable
typedef class{
public:
int i=0;
int j=0;
void create(int a, int b){
i = a;
j = b;
}
// (I've written some currently useless functions, left them in, I might need them)
void update(){
i++;
j++;
}
void manual_update(int increase, string type){
if (type=="both"){
i+=increase;
j+=increase;
}
else if (type=="i"){
i+=increase;
}
else if (type=="j"){
j+=increase;
}
}
}Position;
void updateRow (int row, Position compare, double times, int dimension, string type){
if (type=="else"){
for (int i=0; i<=dimension; i++){
matrix[row][i] -= times * (matrix[compare.j][i]);
}
}
else if (type=="main"){
for (int i=0; i<=dimension; i++){
matrix[row][i] *= times;
}
}
}
double findTimes (Position current, Position compare, string type){
double times;
if (type=="main"){
times = 1 / matrix[current.i][current.j];
}
else if (type=="else"){
times = matrix[current.i][current.j] / matrix[compare.i][compare.j];
}
return times;
}
bool hasFinished (int i, int j){
bool finished = false;
if (matrix[i][j]==1 && i==j){
finished = true;
}
else if (matrix[i][j]==0 && i!=j){
finished = true;
}
return finished;
}
int main(){
int n;
cin>>n;
for (int i=0; i<n; i++){ //reads the matrix
for (int j=0; j<n; j++){
cin>>matrix[i][j];
}
cin>>matrix[i][n];
}
for (int j=0; j<n; j++){
for (int i=0; i<n; i++){
Position current; //current position
current.create(i, j);
Position compare; //position from where the updateRow() will be substracting
if (i!=n-1){
compare.create(i+1, j);
}
else{
compare.create(i-1, j);
}
if (hasFinished (j, i)==false && i==j){
updateRow(i, compare, findTimes(compare, current, "main"), n, "main"); //checks whether it should update or not
}
else if (hasFinished(j, i)==false && i!=j){
updateRow(i, compare, findTimes(compare, current, "else"), n, "else");
}
for (int i=0; i<n; i++){
for (int j=0; j<n+1; j++){
fout<<matrix[i][j]<<" "; //I outputed each step to a file to debug, never mind this
}
fout<<"\n";
}
fout<<"\n";
}
}
for (int i=0; i<n; i++){
cout<<matrix[i][n]<<"\n"; //Print result
}
}
|