1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| #include <iostream> #include <cstdio> #include <cmath> using namespace std; const int N = 110; const double eps = 1e-4; int n; double A[N][N]; int Gauss() { int c = 0, r = 0; for (; c < n; c++) { int t = r; for (int i = r; i < n; i++) if (fabs(A[i][c]) > fabs(A[t][c])) t = i; if (fabs(A[t][c]) < eps) continue; for (int i = c; i <= n; i++) swap(A[t][i], A[r][i]); for (int i = n; i >= c; i--) A[r][i] /= A[r][c]; for (int i = r + 1; i < n; i++) if (fabs(A[i][c]) > eps) for (int j = n; j >= c; j--) A[i][j] -= A[r][j] * A[i][c]; r++; } if (r < n) { for (int i = r; i < n; i++) if (fabs(A[i][n]) > eps) return 1; return 2; } for (int i = n - 1; i >= 0; i--) for (int j = i + 1; j < n; ++j) A[i][n] -= A[i][j] * A[j][n]; return 0; } int main() { cin >> n; for (int i = 0; i < n; i++) for (int j = 0; j <= n; j++) cin >> A[i][j]; int t = Gauss(); if (t == 0) for (int i = 0; i < n; i++) printf("x%d=%.2f\n", i + 1, A[i][n]); else if (t == 1) cout << -1; else if (t == 2) cout << 0; return 0; }
|