zhang_kevin @ 2024-07-23 11:21:42
#include<bits/stdc++.h>
using namespace std;
int n, m;
double a[60][60], eps = 1e-8, t;
inline void check(){
for(int i = 1; i <= n; i++){
bool f1 = true, f2 = true;
for(int j = 1; j <= n + 1; j++){
if(a[i][j] != 0) f1 = false;
if(a[i][j] != 0 && j != n + 1) f2 = false;
}
if(f1) puts("0"), exit(0);
if(f2 && a[i][n+1] != 0) puts("-1"), exit(0);
}
return;
}
int main(){
cin >> n;
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; m = ++j){
for(int i = j + 1; i <= n; i++) if(fabs(a[i][j]) > fabs(a[m][j])) m = i;
check();
for(int i = 1; i <= n + 1; i++) swap(a[j][i], a[m][i]);
check();
if(fabs(a[j][j]) < eps) puts("-1"), exit(0);
check();
for(int i = n + 1; i >= j; i--) a[j][i] /= a[j][j];
check();
for(int i = 1, k; i <= n; i++) if(i != j) for(t = a[i][j] / a[j][j], k = 1; k <= n + 1; k++) a[i][k] -= a[j][k] * t;
check();
}
for(int i = 1; i <= n; i++) cout << "x" << i << "=" << fixed << setprecision(2) << a[i][n+1] << endl;
return 0;
}
代码目前可以正确求解,但是分不清无解和无数解。