用C语言编写一个求定积分的程序

2024-11-16 01:27:36
推荐回答(4个)
回答1:

这是辛普森积分法。
给你写了fun_1( ),fun_2(),请自己添加另外几个被积函数。
调用方法 t=fsimp(a,b,eps,fun_i);
a,b --上下限,eps -- 迭代精度要求。
#include
#include
#include
double fun_1(double x)
{
return 1.0 + x ;
}
double fun_2(double x)
{
return 2.0 * x + 3.0 ;
}

double fsimp(double a,double b,double eps, double (*P)(double))
{
int n,k;
double h,t1,t2,s1,s2,ep,p,x;
n=1; h=b-a;
t1=h*(P(a)+P(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+P(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 main()
{
double a,b,eps,t;
a=0.0; b=3.141592653589793238; eps=0.0000001;
// a definite integral by Simpson Method.
t=fsimp(a,b,eps,fun_1);
printf("%g\n",t);
t=fsimp(a,b,eps,fun_2);
printf("%g\n",t);
// ...
printf("\n Press any key to quit...");
getch();
}

回答2:

#include
#include

int main ()
{
float integral(float a,float b,float (*p)(float,float));
float a,b;
printf("please enter a and b:\n");
scanf("%f%f",&a,&b);
int n;
float f1(float,float );
float f2(float,float );
float f3(float,float );
printf("please choose 1,2or3:\n");
scanf("%d",&n);
if(n==1) integral(a,b,f1);
if(n==2) integral(a,b,f2);
if(n==3) integral(a,b,f3);
return 0;
}

float integral( float a,float b,float(*p)(float ,float)) //定义
{

float result;
result=(*p)(a,b); //调用
printf(" %5.2f \n",result);

return 0;
}
float f1(float x,float y)
{
float y0,y1,y2;

y1=x*x*0.5+x;
y2=y*y*0.5+y;
y0=y2-y1;
printf("(1+x)的积分为result1:=\n");
return y0;
}

float f2(float x,float y)
{
float y0,y1,y2; //y2作为原函数的下限的值,y1作为原函数的上限的值,差为y0 作为结果返回
y1=x*x+3.0*x;
y2=pow(y,2)+3.0*y; //y的平方
y0=y2-y1;
printf("(2x+3)的积分为result2:=\n");
return y0;
}
float f3(float x,float y)
{
float y0,y1,y2;
y1=exp(x)+x;
y2=exp(y)+y;
y0=y2-y1;
printf("(exp(x)+1)的积分为result3:\n");
return y0;
}

回答3:

#include
#include
float
f1(float
x)
{
return(1.0+x);
}
float
f2(float
x)
{
return(2.0*x+3.0);
}
float
f3(float
x)
{
return(exp(x)+1);
}
float
f4(float
x)
{
return(pow(1+x,2));
}
float
f5(float
x)
{
return(pow(x,3));
}
float
fsimp(float
a,float
b,float
(*p)(float))
{
float
c,s;
c=(a+b)/2;
s=(b-a)/6*(p(a)+4*p(c)+p(b));
return
s;
}
int
main()
{
float
a,b;
printf("请输入积分下限a的值:");
scanf("%f",&a);
printf("请输入积分上限b的值:");
scanf("%f",&b);
printf("%f\n",fsimp(a,b,f1));
printf("%f\n",fsimp(a,b,f2));
printf("%f\n",fsimp(a,b,f3));
printf("%f\n",fsimp(a,b,f4));
printf("%f\n",fsimp(a,b,f5));
}

回答4:

用小小梯形法。
即i从-PI/2开始,一直以一个较小的量加上去,加到PI
/2为止,对于每一个量应用上的积分元算出结果,加起来就行了。