fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <vector>
  4. #include <cmath>
  5. #include <algorithm>
  6. #include <string>
  7.  
  8. using namespace std;
  9.  
  10. void gauss_elimination(int n, vector<vector<double>>& A) {
  11.  
  12. cout << setprecision(6) << fixed;
  13.  
  14. cout << "--- Gauss Elimination Method ---" << endl;
  15. cout << "Order of Square Matrix: " << n << endl;
  16.  
  17.  
  18. for (int k = 0; k < n; ++k) {
  19. int pivot = k;
  20. for (int i = k + 1; i < n; ++i) {
  21. if (abs(A[i][k]) > abs(A[pivot][k])) {
  22. pivot = i;
  23. }
  24. }
  25. if (pivot != k) {
  26. swap(A[k], A[pivot]);
  27. }
  28.  
  29. if (abs(A[k][k]) < 1e-9) {
  30. cout << "Error: Near-zero pivot detected. Cannot solve." << endl;
  31. return;
  32. }
  33.  
  34. for (int i = k + 1; i < n; ++i) {
  35. double factor = A[i][k] / A[k][k];
  36. for (int j = k; j < n + 1; ++j) {
  37. A[i][j] -= factor * A[k][j];
  38. }
  39. }
  40. }
  41.  
  42.  
  43. cout << "\n--- Upper Triangular Matrix ---" << endl;
  44. for (int i = 0; i < n; ++i) {
  45. for (int j = 0; j < n + 1; ++j) {
  46. cout << setw(10) << A[i][j] << " ";
  47. }
  48. cout << endl;
  49. }
  50. cout << string(65, '-') << endl;
  51.  
  52.  
  53. vector<double> x(n);
  54. for (int i = n - 1; i >= 0; --i) {
  55. double sum = 0.0;
  56. for (int j = i + 1; j < n; ++j) {
  57. sum += A[i][j] * x[j];
  58. }
  59. x[i] = (A[i][n] - sum) / A[i][i];
  60. }
  61.  
  62.  
  63. cout << "\nOutput:" << endl;
  64. cout << "The solution is:" << endl;
  65. for (int i = 0; i < n; ++i) {
  66. cout << "x" << i + 1 << " = " << x[i] << endl;
  67. }
  68. }
  69.  
  70. int main() {
  71. int n = 3;
  72. vector<vector<double>> A = {
  73. {3.0, 6.0, -9.0, 15.0},
  74. {2.0, 4.0, -6.0, 10.0},
  75. {-2.0, -3.0, 4.0, -6.0}
  76. };
  77.  
  78. gauss_elimination(n, A);
  79.  
  80. return 0;
  81. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
--- Gauss Elimination Method ---
Order of Square Matrix: 3
Error: Near-zero pivot detected. Cannot solve.