老早了解了原理,一直没写过
每次消去一个系数,从系数大的开始消,当出现方程提前为0的情况说明无解或者有无穷多解
#include <bits/stdc++.h>
using namespace std;
int n;
#define N 150
const double eps=1e-7;
double a[N][N];
bool Gauss()
{
int r;
double f;
for (int i=0;i<n;i++)
{
r=i;
for (int j=i+1;j<n;j++)
if (fabs(a[j][i])>fabs(a[r][i])) r=j;
if (fabs(a[r][i])<eps) return (false);
if (r!=i)
for (int j=0;j<=n;j++) swap(a[r][j],a[i][j]);
for (int k=i+1;k<n;k++)
{
f=a[k][i]/a[i][i];
for (int j=i;j<=n;j++) a[k][j]-=f*a[i][j];
}
}
for (int i=n-1;i>=0;i--)
{
for (int j=i+1;j<n;j++) a[i][n]-=a[j][n]*a[i][j];
a[i][n]/=a[i][i];
}
return true;
}
int main()
{
freopen("noip.in","r",stdin);
freopen("noip.out","w",stdout);
std::ios::sync_with_stdio(false);
cin>>n;
int x;
for (int i=0;i<n;i++)
for (int j=0;j<=n;j++)
{
cin>>x;
a[i][j]=x;
}
if (!Gauss())
{
cout<<"No Solution"<<endl;
return 0;
}
for (int i=0;i<n;i++) printf("%.2f
",a[i][n]);
return 0;
}
高斯约当消元法 常熟略大但省略回带过程
#include <bits/stdc++.h>
using namespace std;
#define N 150
const double eps=1e-7;
int n;
double a[N][N];
bool Gauss()
{
int now; double f;
for (int i=0;i<n;i++)
{
now=i;
for (int j=i;j<n;j++)
if (fabs(a[now][i])<fabs(a[j][i])) now=j;
if (fabs(a[now][i])<eps) return(0);
if (now!=i)
for (int j=0;j<=n;j++) swap(a[now][j],a[i][j]);
for (int j=0;j<n;j++)
if (j!=i&&fabs(a[j][i])>eps)
{
f=a[j][i]/a[i][i];
for (int k=0;k<=n;k++)
a[j][k]-=f*a[i][k];
}
}
for (int i=0;i<n;i++) a[i][n]/=a[i][i];
return 1;
}
int main()
{
freopen("noip.in","r",stdin);
freopen("noip.out","w",stdout);
std::ios::sync_with_stdio(false);
cin>>n;
int x;
for (int i=0;i<n;i++)
for (int j=0;j<=n;j++)
{
cin>>x;
a[i][j]=x;
}
if (!Gauss())
{
cout<<"No Solution"<<endl;
return 0;
}
for (int i=0;i<n;i++) printf("%.2f
",a[i][n]);
return 0;
}