ChuongV Crame&Gauss
ChuongV Crame&Gauss
ChuongV Crame&Gauss
Code:
#include <iostream>
using namespace std;
int main() {
int n; double a[10][10], coefficients[5][5]; double constants[5];
cout << "Nhap n = ";
cin >> n;
cout << "Nhap ma tran he so an: \n";
for (int i=0; i<n; i++){
for (int j=0; j<n+1; j++){
cin >> a[i][j];
}
}
for (int i=0; i<n; i++)
for (int j=0; j<n; j++) coefficients[i][j] = a[i][j];
for (int i=0; i<n; i++) constants[i] = a[i][n];
solveEquation(coefficients, constants);
return 0;
}
Code:
#include <iostream>
using namespace std;
int main(){
int n; float a[10][10]; float x[10];
cout << "Nhap n = ";
cin >> n;
cout << "Nhap ma tran he so an: \n";
for (int i=1; i<=n; i++){
for (int j=1; j<=n+1; j++){
cin >> a[i][j];
}
}
for (int i=1; i<=n-1; i++){
if (a[i][i]==0){
int j;
for (j=2; j<=n; j++) if (a[j][i] != 0) break;
if (j<=n && i!=j) {
for (int e=1; e<=n+1; e++){
float t=a[i][e]; a[i][e]=a[j][e]; a[j][e]=t;
}
} else break;
}
for (int j=i+1; j<=n; j++){
float m=-1.0*a[j][i]/a[i][i];
for (int k=i; k<=n+1; k++) a[j][k]=a[j][k]+a[i][k]*m;
}
}
cout << "Ma tran tam giac: \n";
for (int i=1; i<=n; i++){
for (int j=1; j<=n+1; j++) cout << a[i][j] << " ";
cout << endl;
}
for (int i=n; i>=1; i--){
float s=a[i][n+1];
for (int j=i+1; j<=n; j++) s-=a[i][j]*x[j];
if (a[i][i]!=0) x[i]=s/a[i][i];
}
cout << "Nghiem cua he phuong trinh lan luot la: \n";
for (int i=1; i<=n; i++) cout << "x[" << i << "] = " << x[i] << endl;
}