急求!!!!!! c程序 用矩形法编一个通用函数求定积分 0到1区间 ∫01x/exdx n=1000 5
1个回答
展开全部
#include <stdio.h>
#include <math.h>
double fun1(double x)
{
return sin(x);
}
double fun2(double x)
{
return cos(x);
}
double fun3(double x)
{
return exp(x);
}
double integral(double a,double b,double (*p)(double))
{
double step=(b-a)/10000;
double x,sum=0;
for(x=a;x<b;x+=step)
sum+=step*(*p)(x);
return sum;
}
main()
{
double a,b,sum,(*p)(double);
int type;
while(1)
{
printf("1:sin(x)\n2:cos(x)\n3:exp(x)\n0: exit\n");
printf("请选择被积函数种类前的序号\n");
scanf("%d",&type);
while(type<0||type>5)
{
printf("输入的序号不正确,请重新输入:");
scanf("%d",&type);
}
switch(type)
{
case 1:
p=fun1;
break;
case 2:
p=fun2;
break;
case 3:
p=fun3;
break;
case 0:
return 0;
}
printf("请输入积分上下限:\n下限a:");
scanf("%lf",&a);
printf("上限b:");
scanf("%lf",&b);
sum=integral(a,b,p);
printf("第%d种函数在(%g,%g)范围内的定积分为:%f.\n",type,a,b,sum);
}
}
#include <math.h>
double fun1(double x)
{
return sin(x);
}
double fun2(double x)
{
return cos(x);
}
double fun3(double x)
{
return exp(x);
}
double integral(double a,double b,double (*p)(double))
{
double step=(b-a)/10000;
double x,sum=0;
for(x=a;x<b;x+=step)
sum+=step*(*p)(x);
return sum;
}
main()
{
double a,b,sum,(*p)(double);
int type;
while(1)
{
printf("1:sin(x)\n2:cos(x)\n3:exp(x)\n0: exit\n");
printf("请选择被积函数种类前的序号\n");
scanf("%d",&type);
while(type<0||type>5)
{
printf("输入的序号不正确,请重新输入:");
scanf("%d",&type);
}
switch(type)
{
case 1:
p=fun1;
break;
case 2:
p=fun2;
break;
case 3:
p=fun3;
break;
case 0:
return 0;
}
printf("请输入积分上下限:\n下限a:");
scanf("%lf",&a);
printf("上限b:");
scanf("%lf",&b);
sum=integral(a,b,p);
printf("第%d种函数在(%g,%g)范围内的定积分为:%f.\n",type,a,b,sum);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询