该程序使用 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;
}
我做错了什么?
答案 0 :(得分: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开始,实际上它们从零开始。
考虑将其更改为:
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];