高斯塞德尔迭代法c++
时间: 2023-11-18 21:52:49 浏览: 143
高斯塞德尔迭代法是一种求解线性方程组的迭代方法,其基本思想是通过不断迭代逼近方程组的解。下面是一个简单的 C++ 实现:
```c++
#include <iostream>
#include <cmath>
using namespace std;
const int MAXN = 100;
const double eps = 1e-6;
double a[MAXN][MAXN], b[MAXN];
double x[MAXN];
int main()
{
int n;
cout << "请输入方程组的未知数个数:";
cin >> n;
cout << "请输入增广矩阵:\n";
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n + 1; j++) {
cin >> a[i][j];
}
}
// 高斯塞德尔迭代
double err = 1e9;
while (err > eps) {
err = 0;
for (int i = 1; i <= n; i++) {
double tmp = b[i];
for (int j = 1; j <= n; j++) {
if (i != j) {
tmp -= a[i][j] * x[j];
}
}
x[i] = tmp / a[i][i];
err += fabs(x[i] - b[i]);
b[i] = x[i];
}
}
cout << "方程组的解为:\n";
for (int i = 1; i <= n; i++) {
cout << "x" << i << " = " << x[i] << endl;
}
return 0;
}
```
阅读全文