高斯消元法求解线性方程组
题目
代码
#include<stdio.h>
#include<iostream>
#include <iomanip>
#define MAXN 100
using namespace std;
int main() {
int n;
double b[MAXN];
double a[MAXN][MAXN];
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n ; j++) {
cin >> a[i][j];
}
cin >> b[i];
}
for (int i = 0; i < n; i++) {
if (a[i][i] == 0) {
cout << "No solution" << endl;
return 0;
}
for (int j = 0; j < i; j++) {
double temp = a[i][j]/a[j][j];
for (int k = 0; k < n; k++) {
a[i][k]=a[i][k]- temp * a[j][k];
}
b[i] = b[i] - temp * b[j];
}
}
for (int i = n-1; i >= 0; i--) {
for (int j = n-1; j > i; j--) {
b[i] -= b[j] * a[i][j];
}
b[i] = b[i] / a[i][i];
if (b[i] < 1.0e-7 && b[i] > -1.0e-7) b[i] = 0;
}
for (int i = 0; i < n; i++) {
cout << fixed << setprecision(2) << b[i] << endl;
}
return 0;
}
|