xclknf @ 2024-05-02 10:45:27
#include <cmath>
#include <cstdio>
#include <iostream>
#include <algorithm>
#define init signed
#define int double
using namespace std;
init n;
int guass[105][105];
void check()
{
bool hs = true, pf = false;
for (init i = 1;i <= n; ++ i)
{
if (guass[i][i] == 0)
{
if (guass[i][n + 1] == 0)
{
pf = true;
}
else
{
hs = false;
}
}
}
if (! hs)
{
cout << -1 << endl;
exit(0);
}
if (pf)
{
cout << 0 << endl;
exit(0);
}
return;
}
init main()
{
ios::sync_with_stdio(false);
cin.tie(0) , cout.tie(0);
cin >> n;
for (init i = 1;i <= n; ++ i)
{
for (init j = 1;j <= n + 1; ++ j)
{
cin >> guass[i][j];
}
}
for (init i = 1;i <= n; ++ i)
{
init maxn_p;
int maxn = 0;
for (init j = i;j <= n; ++ j)
{
if (fabs(guass[j][i]) >= maxn)
{
maxn = fabs(guass[j][i]);
maxn_p = j;
}
}
for (init j = 1;j <= n + 1; ++ j)
{
swap(guass[maxn_p][j] , guass[i][j]);
}
if(guass[i][i] == 0)
{
continue;
}
for (init j = i + 1;j <= n + 1; ++ j)
{
guass[i][j] /= guass[i][i];
}
for (init j = i + 1;j <= n; ++ j)
{
int l = guass[j][i];
for (init k = 1;k <= n + 1; ++ k)
{
guass[j][k] -= l * guass[i][k] ;
}
}
}
for (init i = n - 1;i >= 1; -- i)
{
for (init j = i + 1;j <= n; ++ j)
{
guass[i][n + 1] -= guass[i][j] * guass[j][n + 1];
}
}
check();
for (init i = 1;i <= n; ++ i)
{
printf("x%d=%.2lf\n", i , guass[i][n + 1]);
}
return 0;
}
by RUOHUI @ 2024-07-19 23:44:03
输出无解的时候double的精度问题 if(fabs(gauss[i][n+1])>eps) return -1; 我eps是1e-6严格差不多
by xclknf @ 2024-09-15 15:13:33
thx