澜月019 @ 2024-11-04 18:41:01
80分求调
#include <bits/stdc++.h>
#define ll long long
#define pi acos(-1)
using namespace std;
const long double eps = 1e-9;
long double a[107][107];
int main() {
cout << fixed << setprecision(2);
int n;
cin >> n;
int r = 0;
// 输入矩阵
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n + 1; j++)
cin >> a[i][j];
// 高斯消元过程
for (int j = 1; j <= n; j++) {
int mx = j; // 找最大行
for (int i = j + 1; i <= n; i++) {
if (fabs(a[i][j]) > fabs(a[mx][j]))
mx = i;
}
if(fabs(a[mx][j])<eps) //这一列全是0
continue;
// 交换行
for (int o = 1; o <= n + 1; o++) {
swap(a[j][o], a[mx][o]);
}
// 行归一化
for (int o = n + 1; o >= j; o--) {
a[j][o] /= a[j][j];
}
// 消去其他行的 j 列
for (int i = 1; i <= n; i++) {
if (i != j) {
long double t = a[i][j];
for (int o = j; o <= n + 1; o++) {
a[i][o] -= a[j][o] * t;
}
}
}
r++;
}
// 反向替换计算结果
vector<long double> result(n + 1);
for (int i = n; i >= 1; i--)
{
result[i] = a[i][n + 1];
for (int j = i + 1; j <= n; j++) {
result[i] -= a[i][j] * result[j];
}
}
//cout << r << endl;
if(r<n)
{
for (int i = r + 1; i <= n;i++)
{
if (fabs(a[i][n + 1]) > eps)
{
cout << -1 << endl;
return 0;
}
}
cout << 0 << endl;
//return 0;
}
// 输出解
else
for (int i = 1; i <= n; i++)
cout << "x" << i << "=" << result[i] << endl;
return 0;
}