#include"iostream.h"
#include"math.h"
double c[10][10];
double f(double x)
{
double sum=0;
if(x==0) return 1;
sum=sin(x)/x;
return sum;
}
void initcotes(double c[][10])
{
c[1][0]=c[1][1]=0.5;
c[2][0]=c[2][2]=1.0/6.0;c[2][1]=2.0/3.0;
c[3][0]=c[3][3]=1.0/8.0;c[3][1]=c[3][2]=3.0/8.0;
c[4][0]=c[4][4]=7.0/90.0;c[4][1]=c[4][3]=16.0/45.0;c[4][2]=2.0/15.0;
c[5][0]=c[4][5]=19.0/288.0;c[5][1]=c[5][4]=25.0/96.0;c[5][2]=c[5][3]=25.0/144.0;
}
void Trapezoid(double a,double b)
{
cout<<"梯形公式的結果:"<<(b-a)*(f(a)+f(b))/2<<endl;
}
void MidRect(double a,double b)
{
cout<<"中矩形公式的結果:"<<(b-a)*f((b+a)/2)<<endl;
}
void NewtonCotes(double a,double b)
{
int n,k;double h;
cout<<"請輸入n的值:";
cin>>n;
h=(b-a)/double(n);
double sum=0;
for(k=0;k<=n;k++)
sum+=c[n][k]*f(a+k*h);
cout<<"牛頓-柯特斯公式的結果:"<<(b-a)*sum<<endl;
}
int STrapezoid(double a,double b)
{
int n,k,q;double h;
cout<<"1--復化梯形公式"<<endl;
cout<<"2--復化辛普森求積公式"<<endl;
cout<<"輸入你想進行的操作:";
cin>>q;
cout<<"請輸入n的值:";
cin>>n;
h=(b-a)/double(n);
double sum=0;
sum+=(f(a)+f(b));
for(k=1;k<=n-1;k++) sum+=2*f(a+k*h);
if(q==1)
{
cout<<"復化梯形公式的結果:"<<(h/2)*sum<<endl;
return 1;
}
for(k=0;k<n;k++)
sum+=4*f(a+(k+0.5)*h);
cout<<"復化辛普森求積公式的結果:"<<(h/6)*sum<<endl;
return 1;
}
void main()
{
double a,b;
int p;
cout<<"請輸入積分的下、上限:";
cin>>a>>b;
initcotes(c);
while(1)
{
cout<<"0--退出"<<endl;
cout<<"1--梯形公式"<<endl;
cout<<"2--中矩形公式"<<endl;
cout<<"3--牛頓柯特斯公式:"<<endl;
cout<<"4--復化公式"<<endl;
cout<<"輸入你想進行的操作:";
cin>>p;
switch(p)
{
case 1:Trapezoid(a,b);
case 2:MidRect(a,b);
case 3:NewtonCotes(a,b);
case 4:STrapezoid(a,b);
}
if(p==0) break;
}
}
posted on 2007-06-08 23:27
星夢情緣 閱讀(3004)
評論(2) 編輯 收藏 引用 所屬分類:
數據結構的所有實現程序