请使用C语言代码,分别用crout分解法和Gauss-Seidel迭代法,求解线性方程组。

初始值为:X1(0)=3.8, X2(0)=3.7, X3(0)=4.9
请用C++代码。 精确到小数点后三位。

#include<iostream>
#include<cmath>
using namespace std;
#define N 3
long double a[N][N];
long double b[N];
long double eps;
long double x[N]; //声明系数矩阵,方程右侧值,相对误差分析,解的初始值
void GetData(); //获得数据
void Gauss_Seidel(); //高斯迭代
void Show(); //输出结果
int main()
{
cout<<"======================================="<<endl;
cout<<" gauss_seidel迭代法解方程组"<<endl;
cout<<"======================================="<<endl;
GetData();
Gauss_Seidel();
Show();
return 0;
}
void GetData()
{
for(int i=0;i<3;i++)
{
cout<<"系数矩阵第"<<i+1<<"行:";
for(int j=0;j<3;j++) cin>>a[i][j];
}
cout<<"方程右侧值:";
cin>>b[0]>>b[1]>>b[2];
cout<<"误差允许量:";
cin>>eps;
cout<<"解的初始值:";
cin>>x[0]>>x[1]>>x[2];
}
void Gauss_Seidel()
{
int flag;double xold,sum,error;
do
{
flag=0;
for(int i=0;i<3;i++)
{
xold=x[i];
sum=0.0;
for(int j=0;j<3;j++)
if(j!=i) sum+=a[i][j]*x[j];
x[i]=(b[i]-sum)/a[i][i];
error=fabs(xold-x[i])/x[i];
if(error>=eps) flag=1;
}
}while(flag==1);
}
void Show()
{
cout<<"结果是:"<<endl;
for(int i=0;i<3;i++)
cout<<"x"<<i+1<<" "<<x[i]<<endl;
}
你可以看看我的思路,但是这道题数字问题,在我的电脑上运行时总是过界,简单的数字还可以,不好意思追问

如果用crout分解法应该如何编写?

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-12-20
# include <math.h>
# include <stdio.h>
# define max 100
# define EPS 1e-6
float a[3][3]={{1,4,3},{2,1,-10},{8,1,2}};
float b[3]={35,62,46};
float x[3]={0,0,0};
float y[3];
float S(int m)
{
int n;
float S=0;
float y;
for (n=0;n<3;n++)
{
if(m==n){}
else
{
S+=a[m][n]*x[n];
}
}
y=(b[m]-S)/a[m][m];
return y;
}
main()
{
int i;
int F,T=1,k=1;
do
{
F=0;
if(T)
{T = 0;}
else
{
k++;
for(i=0;i<3;i++)
{
x[i]=y[i];
}
}
for (i=0;i<3;i++)
{
y[i]=S(i);
}
for (i=0;i<3;i++)
{
if(fabs(x[i]-y[i])>EPS)
{
F=1;
}
}
printf("%d\n",k);
}
while(((F==1)&&k!=max));
printf("迭代次数:%d\n",k);
for(i=0;i<3;i++)
{
printf("x[%d]=%1.6f\n",i,y[i]);
}
}本回答被网友采纳
第2个回答  2012-03-31
#include<iostream> #include<cmath> using namespace std; #define N 3 long double a[N][N]; long double b[N]; long double eps; long double x[N]; //声明系数矩阵,方程右侧值,相对误差分析,解的初始值 void GetData(); //获得数据 void Gauss_Seidel(); //高斯迭代 void Show(); //输出结果 int main() { cout<<"======================================="<<endl; cout<<" gauss_seidel迭代法解方程组"<<endl; cout<<"======================================="<<endl; GetData(); Gauss_Seidel(); Show(); return 0; } void GetData() { for(int i=0;i<3;i++) { cout<<"系数矩阵第"<<i+1<<"行:"; for(int j=0;j<3;j++) cin>>a[i][j]; } cout<<"方程右侧值:"; cin>>b[0]>>b[1]>>b[2]; cout<<"误差允许量:"; cin>>eps; cout<<"解的初始值:"; cin>>x[0]>>x[1]>>x[2]; } void Gauss_Seidel() { int flag;double xold,sum,error; do { flag=0; for(int i=0;i<3;i++) { xold=x[i]; sum=0.0; for(int j=0;j<3;j++) if(j!=i) sum+=a[i][j]*x[j]; x[i]=(b[i]-sum)/a[i][i]; error=fabs(xold-x[i])/x[i]; if(error>=eps) flag=1; } }while(flag==1); } void Show() { cout<<"结果是:"<<endl; for(int i=0;i<3;i++) cout<<"x"<<i+1<<" "<<x[i]<<endl;