-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasicgauss.cpp
105 lines (78 loc) · 1.62 KB
/
basicgauss.cpp
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
#include<bits/stdc++.h>
using namespace std;
double matrix[10][10];
double coeff[10];
double sum=0.0;
double a=0.0;
int n;
void swap(int row)
{
for(int i=1;i<=n;i++)
{
swap(matrix[row][i],matrix[1][i]);
}
}
int main()
{
cout<<"Enter n : "<<endl;
cin>>n;
for(int i=1;i<=n;i++)
{
cout<<"Enter coeff for eq "<<i<<endl;
for(int j=1;j<=n+1;j++)
{
cin>>matrix[i][j];
}
}
for(int i=1;i<=n;i++)
{
// cout<<"Enter coeff for eq "<<i<<endl;
for(int j=1;j<=n+1;j++)
{
cout<<matrix[i][j]<<" ";
}
puts("");
}
puts("");
if(matrix[1][1]==0)
{
for(int i=2;i<=n;i++)
{
if(matrix[i][1]!=0)
{
swap(i);
break;
}
}
}
for(int i=1;i<=n-1;i++)
{
for(int j=1;j<=n;j++)
{
if(i<j)
{
a=matrix[j][i]/matrix[i][i];
for(int k=1;k<=n+1;k++)
{
matrix[j][k]=matrix[j][k]-(a*matrix[i][k]);
}
}
}
}
coeff[n]=matrix[n][n+1]/matrix[n][n];
for(int i=n-1;i>=1;i--)
{ sum=0.0;
for(int j=i+1;j<=n;j++)
{
sum+=coeff[j]*matrix[i][j];
// sum+=coeff[j]*matrix[i][j];
}
coeff[i]=(matrix[i][n+1]-sum)/matrix[i][i];
}
puts("");
for(int i=1;i<=n;i++)
{
cout<<"X"<<i<<" : "<<coeff[i]<<endl;
puts("");
}
}