fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int n;
  4. vector<vector<double>> A;
  5.  
  6. void ge() {
  7. // Forward Elimination
  8. for (int k = 0; k < n; k++) {
  9. for (int i = k + 1; i < n; i++) {
  10. double r = A[i][k] / A[k][k];
  11. for (int j = k; j <= n; j++) {
  12. A[i][j] -= r * A[k][j];
  13. }
  14. }
  15. }
  16.  
  17. // Back Substitution
  18. vector<double> ans(n);
  19. for (int i = n - 1; i >= 0; i--) {
  20. ans[i] = A[i][n];
  21. for (int j = i + 1; j < n; j++) {
  22. ans[i] -= A[i][j] * ans[j];
  23. }
  24. ans[i] /= A[i][i];
  25. }
  26.  
  27. // Printing Result
  28. cout << "\nSolutions:\n";
  29. for (int i = 0; i < n; i++) {
  30. cout << "x" << i + 1 << " : " << ans[i] << endl;
  31. }
  32. }
  33.  
  34. int main() {
  35. cout << "Enter vars: \n";
  36. cin >> n;
  37. A = vector<vector<double>>(n, vector<double>(n + 1, 0));
  38.  
  39. cout << "Enter the augmented matrix (row-wise):\n";
  40. for (int i = 0; i < n; i++) {
  41. for (int j = 0; j <= n; j++) {
  42. cin >> A[i][j];
  43. }
  44. }
  45.  
  46. ge();
  47. return 0;
  48. }
Success #stdin #stdout 0.01s 5288KB
stdin
3
5 10 1 28
1 1 1 6
4 8 3 29
stdout
Enter vars: 
Enter the augmented matrix (row-wise):

Solutions:
x1 : 1
x2 : 2
x3 : 3