题目来源:大工慕课 链接
作者:Caleb Sung
题目要求
(27)编写积分函数求任意函数的积分,并用写好的函数,求三角函数与幂指数的定积分。可参看上机指导书P135 E7.2 书上使用的是矩形积分,可以尝试用梯形积分。同时改变n的取值看对积分函数值的影响,体会高数中积分的定义。如果参考上机指导书,书上函数中for(i=0;i<=n;i++),这一行写错了,大家可以作为一个改错练习。 开始可让 ac=0,bc=3.1415926,算三角函数的积分,看函数是否编写正确。
题目代码
#include<stdio.h>
#include <math.h>
int main()
{
int n=1000;
double ac=-1,bc=1,ae=0,be=2,c,(*p)();
/*double ac=0,bc=3.1415926,ae=0,be=2,c,(*p)();*/
double jiff();
p=cos;
c=jiff(ac,bc,n,p);
printf("the definite integral of cosx -1 to 1 is: %f\n",c);
p=exp;
c=jiff(ae,be,n,p);
printf("the definite integral of exp 0 to 2 is:%f\n",c);
return 0;
}
double jiff(double a,double b, int n, double (*p)())
{
//******begin************************
//*******end*************************
}
参考解答
可参考之前我写的同类试题参考解答:
https://blog.csdn.net/qq_41933331/article/details/80256500
double jiff(double a,double b, int n, double (*p)())
{
//******begin************************
double ha, hb, result=0;
int i;
for(i=0; i<n; i++){
ha = p(a+i*(b-a)/n);
hb = p(a+(i+1)*(b-a)/n);
result += ((ha + hb)*(b-a)/n)/2.0;
}
return result;
//*******end*************************
}
运行结果
the definite integral of cosx -1 to 1 is: 1.682941
the definite integral of exp 0 to 2 is:6.389058