jordan
unknown
plain_text
9 days ago
1.9 kB
4
Indexable
Never
#include<bits/stdc++.h> using namespace std; void print(vector<vector<double>>& arr, int n) { for(int i = 0; i < n; i++) { for(int j = 0; j < n + 1; j++) { cout << arr[i][j] << " "; } cout << endl; } } int main() { cout<<"Enter the number of equations: " << endl; int n; cin >> n; vector<vector<double>> arr(n, vector<double>(n+1)); vector<double> x(n); cout << "Enter the augmented matrix coefficients row-wise: " << endl; for(int i = 0; i < n; i++) { for(int j = 0; j < n + 1; j++) { cin >> arr[i][j]; } } for(int i = 0; i < n; i++) { // Partial Pivoting if(arr[i][i] == 0) { bool row_swapped = false; for(int j = i + 1; j < n; j++) { if(arr[j][i] != 0) { swap(arr[i], arr[j]); row_swapped = true; break; } } if(!row_swapped) { cout << "No unique solution exists due to zero diagonal element." << endl; return 0; } } double pivot = arr[i][i]; for(int j = 0; j <= n; j++) { arr[i][j] /= pivot; } for(int j = 0; j < n; j++) { if(j != i) { double ratio = arr[j][i]; for(int k = 0; k <= n; k++) { arr[j][k] -= ratio * arr[i][k]; } } } cout << "Matrix after step " << i + 1 << " of elimination:" << endl; print(arr, n); } cout << "Solution is: " << endl; for(int i = 0; i < n; i++) { cout << "x" << i + 1 << " = " << arr[i][n] << endl; } return 0; } /*3 1 1 1 9 2 -3 4 13 3 4 5 40 */
Leave a Comment