全主元高斯消元法c++
时间: 2023-12-22 15:28:23 浏览: 71
用C++实现高斯列主元消去法
3星 · 编辑精心推荐
全主元高斯消元法是一种解线性方程组的方法,它可以通过消元和回代的方式求解方程组的解。以下是一个C++实现的例子:
```c++
#include <iostream>
#include <cmath>
using namespace std;
const int MAXN = 100;
const double eps = 1e-10;
class GAUS {
private:
int n;
double a[MAXN][MAXN], b[MAXN];
int p[MAXN], q[MAXN];
public:
GAUS(int n) : n(n) {}
void input() {
cout << "请输入系数矩阵A和常数向量B:" << endl;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> a[i][j];
}
cin >> b[i];
}
}
void gauss() {
for (int i = 1; i <= n; i++) {
p[i] = q[i] = i;
}
for (int k = 1; k <= n; k++) {
double maxa = 0;
int maxp = 0, maxq = 0;
for (int i = k; i <= n; i++) {
for (int j = k; j <= n; j++) {
if (fabs(a[p[i]][q[j]]) > maxa) {
maxa = fabs(a[p[i]][q[j]]);
maxp = i;
maxq = j;
}
}
}
if (maxa < eps) {
cout << "矩阵奇异,无法求解!" << endl;
return;
}
if (maxp != k) {
swap(p[k], p[maxp]);
}
if (maxq != k) {
swap(q[k], q[maxq]);
}
for (int i = k + 1; i <= n; i++) {
double f = a[p[i]][q[k]] / a[p[k]][q[k]];
b[p[i]] -= f * b[p[k]];
for (int j = k + 1; j <= n; j++) {
a[p[i]][q[j]] -= f * a[p[k]][q[j]];
}
}
}
}
void output() {
cout << "方程组的解为:" << endl;
for (int i = n; i >= 1; i--) {
double sum = 0;
for (int j = i + 1; j <= n; j++) {
sum += a[p[i]][q[j]] * b[p[j]];
}
b[p[i]] = (b[p[i]] - sum) / a[p[i]][q[i]];
}
for (int i = 1; i <= n; i++) {
cout << "x" << i << " = " << b[p[i]] << endl;
}
}
};
int main() {
GAUS c(4);
c.input();
c.gauss();
c.output();
return 0;
}
```
阅读全文