分别采用梯形法、矩形法和辛普森法计算函数f(x)=e^(3x)+x^7在区[1,3]上的定积分。

2025-02-23 07:05:18
推荐回答(1个)
回答1:

#include
#include
#include
float fx(float x){

return (exp(3.0*x)+pow(x,7));
}
float tixing(float(*fun)(float x),float a,float b,int n)
{
float s,h,y;
int i;
s=(fun(a)+fun(b))/2;
h=(b-a)/n;
for(i=1;i s=s+fun(a+i*h);
y=s*h;
return y;
}
float juxing(float(*fun)(float x),float a,float b,int n){

double h;
double fx;
double x;
int i;
double sum=0;
h=fabs(a-b)/100;
x=a;
for(i=0;i<100;i++)
{
fx=fun(x+i*h+h/2);
sum=sum+fx;
}
return sum*h;
}
float fsimp(float(*fun)(float x),float a,float b,int eps)
{
int n,k;
double h,t1,t2,s1,s2,ep,p,x;
n=1; h=b-a;
t1=h*(fun(a)+fun(b))/2.0;
s1=t1;
ep=eps+1.0;
while (ep>=eps)
{
p=0.0;
for (k=0;k<=n-1;k++)
{
x=a+(k+0.5)*h;
p=p+fun(x);
}
t2=(t1+h*p)/2.0;
s2=(4.0*t2-t1)/3.0;
ep=fabs(s2-s1);
t1=t2; s1=s2; n=n+n; h=h/2.0;
}
return(s2);
}
void menu(){

system("cls");
printf("1.梯形法\n2.矩形法\n3.辛普森法\n4.退出\n");

}
int main()
{
int c=0;
menu();
while(1){

scanf("%d",&c);
switch(c){

case 1:printf("梯形法:%f\n",tixing(fx,1,3,1000));
break;
case 2:printf("矩形法:%f\n",juxing(fx,1,3,1000));
break;
case 3:printf("辛普森法:%f\n",fsimp(fx,1,3,1000));
break;
case 4:return 0;
}
}
}