首页 > 其它 > 题目详情
写一个用矩形法求定积分的通用函数,分别求正弦,余弦和自然对数幂函数的定积分.要能直接运行的代码,能简短的介绍几句更好.
题目内容:
写一个用矩形法求定积分的通用函数,分别求正弦,余弦和自然对数幂函数的定积分.
要能直接运行的代码,能简短的介绍几句更好.优质解答
#include
#include
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;xsum+=step*(*p)(x);
return sum;
}
main()
{
double a,b,sum,(*p)();
int type;
while(1)
{
printf("1:sin(x)\n2:cos(x)\n3:exp(x)\n0:结束\n");
printf("请选择被积函数的种类(输入种类前的序号):\n");
scanf("%d",&type);
while(type5)
{
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
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;xsum+=step*(*p)(x);
return sum;
}
main()
{
double a,b,sum,(*p)();
int type;
while(1)
{
printf("1:sin(x)\n2:cos(x)\n3:exp(x)\n0:结束\n");
printf("请选择被积函数的种类(输入种类前的序号):\n");
scanf("%d",&type);
while(type5)
{
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);
}
}
本题链接: