ChuongV Crame&Gauss

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

1.

Phương pháp Crame

Code:
#include <iostream>
using namespace std;

double determinant4x4(double mat[4][4]) {


double det = 0;
for (int i = 0; i < 4; ++i) {
det += mat[0][i] * (mat[1][(i + 1) % 4] * (mat[2][(i + 2) % 4] * mat[3][(i +
3) % 4] - mat[2][(i + 3) % 4] * mat[3][(i + 2) % 4]) );
}
return det;
}

double determinant5x5(double mat[5][5]) {


double det = 0;
for (int i = 0; i < 5; ++i) {
double submatrix[4][4];
for (int j = 1; j < 5; ++j) {
int col = 0;
for (int k = 0; k < 5; ++k) {
if (k != i) {
submatrix[j - 1][col] = mat[j][k];
++col;
}
}
}
det += (i % 2 == 0 ? 1 : -1) * mat[0][i] * determinant4x4(submatrix);
}
return det;
}

void solveEquation(double coefficients[5][5], double constants[5]) {


double det_A = determinant5x5(coefficients);
for (int i = 0; i < 5; ++i) {
double temp[5][5];
for (int j = 0; j < 5; ++j) {
for (int k = 0; k < 5; ++k) {
temp[j][k] = coefficients[j][k];
}
}
for (int j = 0; j < 5; ++j) {
temp[j][i] = constants[j];
}
double det_Ai = determinant5x5(temp);
double solution = det_Ai / det_A;
cout << "x" << i + 1 << " = " << solution << endl;
}
}

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;
}

Màn hình kết quả:


2. Phương pháp Gauss

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;
}

Màn hình kết quả:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy