采用高斯消元法,求解线性方程组
#include <bits/stdc++.h>
#define io cin.tie(0), cout.tie(0), ios::sync_with_stdio(false)
#define LL long long
#define ULL unsigned long long
#define EPS 1e-7
#define INF 0x7fffffff
#define SUB -INF - 1
using namespace std;
double a[150][150], ans[150];
int main()
{
io;
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n + 1; j++)
scanf("%lf", &a[i][j]);
for (int i = 1; i <= n; i++)
{
int maxs = i;
for (int j = i + 1; j <= n; j++)
if (fabs(a[j][i]) > fabs(a[maxs][i]))
maxs = j;
if (fabs(a[maxs][i]) < EPS)
{
puts("No Solution");
return 0;
}
if (i != maxs)
swap(a[i], a[maxs]);
double div = a[i][i];
for (int j = i; j <= n + 1; j++)
a[i][j] /= div;
for (int j = i + 1; j <= n; j++)
{
div = a[j][i];
for (int k = i; k <= n + 1; k++)
a[j][k] -= a[i][k] * div;
}
}
ans[n] = a[n][n + 1];
for (int i = n - 1; i >= 1; i--)
{
ans[i] = a[i][n + 1];
for (int j = i + 1; j <= n; j++)
ans[i] -= (a[i][j] * ans[j]);
}
for (int i = 1; i <= n; i++)
printf("x[%d]=%.2lf\n", i, ans[i]);
return 0;
}