您的位置:首页 > 编程语言 > C语言/C++

超松弛法(C++ 数值分析)

2010-10-09 14:19 471 查看
#include <iostream>

#include <cmath>

#include <iomanip>

using namespace std;

const int n=4;

const double w=1.15; //w不能定义为float类型

int main()

{

float a

,b
;

int i,j;

void gauss(float a[]
,float b
); //声明

cout<<"please input a[i][j]:"<<endl;

for(i=0;i<n;i++)

for(j=0;j<n;j++)

cin>>a[i][j];

cout<<endl;

cout<<"please input b[i]:"<<endl;

for(i=0;i<n;i++)

cin>>b[i];

cout<<'/n';

gauss(a,b); //调用

return 0;

}

void gauss(float a[]
,float b
) //求解

{

int i,k=0;

float max_cha(float x1
,float x2
);

float qiu_he1(float a[]
,float x1
,int i);

float qiu_he2(float a[]
,float x2
,int i);

float cha,he1,he2;

float x1
,x2
;

cout<<setiosflags(ios::right);

for(i=0;i<=n;i++)

{

if(i==0)

cout<<setw(10)<<"k";

else

cout<<setw(14)<<"x"<<i;

}

cout<<'/n'<<setw(10)<<k;

for(i=0;i<n;i++)

{

x1[i]=0;

cout<<setiosflags(ios::right);

cout<<setw(15)<<x1[i];

}

cout<<endl;

do

{k++;

cout<<setw(10)<<k;

for(i=0;i<n;i++)

{

he1=qiu_he1(a,x1,i);

he2=qiu_he2(a,x2,i);

x2[i]=x1[i]+w/a[i][i]*(b[i]-he2-he1);

cout<<setw(15)<<x2[i];

}

cout<<endl;

cha=max_cha(x1,x2);

for(i=0;i<n;i++)

x1[i]=x2[i];

}

while(fabs(cha)>0.00001);

cout<<endl;

}

float qiu_he1(float a[]
,float x1
,int i)

{

float sum=0;

int j;

for(j=i;j<n;j++)

sum+=a[i][j]*x1[j];

return (sum);

}

float qiu_he2(float a[]
,float x2
,int i)

{

float sum=0;

int j;

for(j=0;j<i;j++)

sum+=a[i][j]*x2[j];

return (sum);

}

float max_cha(float x1
,float x2
)

{

int j;

float max=fabs(x1[0]-x2[0]);

float cha;

for(j=0;j<n;j++)

{

cha=fabs(x1[j]-x2[j]);

if(max<cha)

max=cha;

}

return (max);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: