# 洛谷P3389：【模板】高斯消元法

CODE：

#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<stdio.h>
#include<algorithm>
using namespace std;

const int maxn=110;
const double eps=1e-8;

double a[maxn][maxn];
int n;

double Abs(double x)
{
if (x>0.0) return x;
return -x;
}

int Gauss()
{
int R,r=1,c=1;
while ( r<=n && c<=n )
{
R=r;
for (int i=r+1; i<=n; i++)
if ( Abs(a[i][c])>Abs(a[R][c]) ) R=i;

if (Abs(a[R][c])<eps) r--;
else
{
for (int i=c; i<=n+1; i++) swap(a[R][i],a[r][i]);
for (int i=r+1; i<=n; i++)
if ( Abs(a[i][c])>eps )
{
for (int j=c+1; j<=n+1; j++)
a[i][j]=a[i][j]/a[i][c]-a[r][j]/a[r][c];
a[i][c]=0.0;
}
}

r++;
c++;
}

for (int i=r; i<=n; i++)
if ( Abs(a[i][n+1])>eps ) return -1;
if (r<=n) return n-r+1;

for (int i=n; i>=1; i--)
{
for (int j=i+1; j<=n; j++) a[i][n+1]-=a[i][j]*a[j][n+1];
a[i][n+1]/=a[i][i];
}
return 0;
}

int main()
{
freopen("3389.in","r",stdin);
freopen("3389.out","w",stdout);

scanf("%d",&n);
for (int i=1; i<=n; i++)
for (int j=1; j<=n+1; j++)
{
int x;
scanf("%d",&x);
a[i][j]=((double)x);
}

int temp=Gauss();
if (temp!=0) printf("No Solution\n");
else
for (int i=1; i<=n; i++) printf("%.2lf\n",a[i][n+1]);

return 0;
}

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客