代码如下
#include <bits/stdc++.h>
using namespace std;
const double eps = 1e-7;
struct matrix {
vector<vector<double>> mat;
int n, m;
matrix(int n, int m) : n(n), m(m) {
mat.resize(n + 1, vector<double>(m + 1, 0));
}
vector<double> &operator[](int x) {
return mat[x];
}
};
bool gauss(matrix &a, int n) {
for (int i = 1; i <= n; i++) {
int p = i;
for (int j = i + 1; j <= n; j++) {
if (fabs(a[p][i]) < fabs(a[j][i])) {
p = j;
}
}
if (p != i) {
swap(a[p], a[i]);
}
if (fabs(a[p][i]) < eps) {
return 0;
}
for (int j = i + 1; j <= n; j++) {
double factor = a[j][i] / a[i][i];
for (int k = i; k <= n + 1; k++) {
a[j][k] -= factor * a[i][k];
}
}
}
for (int i = n; i >= 1; i--) {
for (int j = i + 1; j <= n; j++) {
a[i][n + 1] -= a[j][n + 1] * a[i][j];
}
a[i][n + 1] /= a[i][i];
}
return 1;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0), cout.setf(ios::fixed);
int n;
cin >> n;
matrix a(n, n + 1);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n + 1; j++) {
cin >> a[i][j];
}
}
if (gauss(a, n) == 0) {
cout << "No Solution" << endl;
} else {
for (int i = 1; i <= n; i++) {
cout << setprecision(2) << a[i][n + 1] << endl;
}
}
return 0;
}