【问题标题】:gauss siedel iterative method in c++C ++中的高斯赛德尔迭代方法
【发布时间】:2015-09-24 10:44:21
【问题描述】:

此程序使用Gauss-Siedel 迭代过程求解线性方程组,其中初始近似为:(x0, y0, z0) = (0, 0, 0)

但是当我运行它时,窗口在我输入矩阵输入后立即关闭,无法完成整个程序。

代码如下:

#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;

int main(){
    float x1, x2, x3, x1new, x2new, x3new, sum;
    float a[3][3], b[3], error[3];
    x1 = x2 = x3 = 0;
    x1new = x2new = x3new = 0;

    cout <<"enter the coefficients of equation or matrix a \n";
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++)
            cin >> a[i][j];
    }
    cout <<" \n enter the right side values of equation or matrix b ";
    for(int i = 0; i < 3; i++)
        cin >> b[i];

    for(int i = 0; i < 3; i++){
        error[i] = 1;
    }

    while((error[0]| | error[1]| | error[2]) > =0.00001){
        x1 = (b[0] - (a[0][1] * x2 + a[0][2] * x3)) / a[0][0];
        x2 = (b[1] - (a[1][0] * x1 + a[1][2] * x3)) / a[1][1];
        x3 = (b[2] - (a[2][0] * x1 + a[2][1] * x2)) / a[2][2];
        error[0] = abs(x1) - abs(x1new);
        error[1] = abs(x2) - abs(x2new);
        error[2] = abs(x3) - abs(x3new);
        x1new = x1;
        x2new = x2;
        x3new = x3;
    }
    cout <<"\n the values of variables x1,x2 and x3 are:";
    cout << x1 << x2 << x3;
}

问题:

我做错了什么?

【问题讨论】:

  • [4 -1 1;4 -8 1;-2 1 5] [7 -21 15]
  • 您已经编辑了帖子,但当数组仅分配给 3 个元素时,我仍然看到在 b[3] 中对下标 3 的引用。这将使程序崩溃。 b[3] 中没有数据,即使您将分配扩展为 float b[4](3 是 b 中的第 4 个元素),您仍然不会在 b[3] 中放置任何内容。与 [3] 相同。那些不应该从 0 到 2 索引,就像其他所有东西一样,还是你认为它应该从 1 到 3 索引?

标签: c++ sparse-matrix


【解决方案1】:

给定:

float a[3][3],b[3],error[3];

明显的问题是:

x1=(b[1]-(a[1][2]*x2+a[1][3]*x3))/a[1][1];
x2=(b[2]-(a[2][1]*x1+a[2][3]*x3))/a[2][2];
x3=(b[3]-(a[3][1]*x1+a[3][2]*x2))/a[3][3];

其中 3 的所有索引都引用了未分配的第 4 个索引。

这会在 Linux 上导致段错误,在 Windows 中会导致访问冲突。

此代码的总体视图表明索引被认为从 1 开始,而实际上它们从 0 开始。

考虑将其更改为:

x1=(b[0]-(a[0][1]*x2+a[0][2]*x3))/a[0][0];
x2=(b[1]-(a[1][0]*x1+a[1][2]*x3))/a[1][1];
x3=(b[2]-(a[2][0]*x1+a[2][1]*x2))/a[2][2];

【讨论】:

  • 非常感谢 :) 我已经纠正了我的错误,但仍然无法找到解决方案
  • @ritz 欢迎来到 SO!对帮助您的宝贵信息的作者表示感谢的首选方式是赞成接受给定的答案。在你的情况下,只有后者适用,直到你达到 15 声望。
猜你喜欢
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-14
  • 1970-01-01
  • 2011-02-03
  • 2010-12-16
相关资源
最近更新 更多