fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <iomanip>
  4. #include <cmath>
  5. using namespace std;
  6.  
  7. int main() {
  8. int n;
  9. cout << "Enter the order of square matrix: ";
  10. cin >> n;
  11.  
  12. vector<vector<double>> a(n, vector<double>(n + 1));
  13. vector<double> x(n);
  14.  
  15. cout << "Enter the elements of augmented matrix row-wise:\n";
  16. for (int i = 0; i < n; i++) {
  17. for (int j = 0; j <= n; j++) {
  18. cin >> a[i][j];
  19. }
  20. }
  21.  
  22. // Forward Elimination
  23. for (int i = 0; i < n; i++) {
  24. // Partial Pivoting
  25. for (int k = i + 1; k < n; k++) {
  26. if (fabs(a[i][i]) < fabs(a[k][i])) {
  27. swap(a[i], a[k]);
  28. }
  29. }
  30.  
  31. for (int k = i + 1; k < n; k++) {
  32. double factor = a[k][i] / a[i][i];
  33. for (int j = 0; j <= n; j++) {
  34. a[k][j] -= factor * a[i][j];
  35. }
  36. }
  37. }
  38.  
  39. // Backward Substitution
  40. for (int i = n - 1; i >= 0; i--) {
  41. x[i] = a[i][n];
  42. for (int j = i + 1; j < n; j++) {
  43. x[i] -= a[i][j] * x[j];
  44. }
  45. x[i] /= a[i][i];
  46. }
  47.  
  48. // Output the solution
  49. cout << "\nThe solution is:\n";
  50. for (int i = 0; i < n; i++) {
  51. cout << "x" << i + 1 << " = " << fixed << setprecision(6) << x[i] << endl;
  52. }
  53.  
  54. return 0;
  55. }
  56.  
Success #stdin #stdout 0.01s 5320KB
stdin
3 6 -9 15
2 4 -6 10
-2 -3 4 -6
stdout
Enter the order of square matrix: Enter the elements of augmented matrix row-wise:

The solution is:
x1 = -nan
x2 = -inf
x3 = -inf