前言
了解了函数指针和梯形定积分求解步骤
正文
- 函数指针
函数返回值类型 (* 指针变量名) (函数参数列表);
int Func(int x); /*声明一个函数*/
int (*p) (int x); /*定义一个函数指针*/
p = Func; /*将Func函数的首地址赋给指针变量p*/
- 梯形定积分求解
左边的是曲线的梯形定积分形式,右边的曲线的矩形定积分形式
思想都差不多,把区间划分成n等分,然后用矩形或梯形公式来计算每一份,接着把n份的值累加起来就是该曲线区间的近似面积
代码
参考资料答案代码
#include <stdio.h>
#include <math.h>
float collect(float s,float t,int n,float(*p)(float x));
float fun1(float x);
float fun2(float x);
int main(){
int n,flag;
float a,b,v=0.0;
printf("input the count range(from A to B)and the number of sections\n");
scanf("%f%f%d",&a,&b,&n);//给出上线,下线和n等份
printf("Enter you choice:'1'for fun1,'2'for fun2\n");
scanf("%d",&flag);//选择函数
if(flag==1){
v=collect(a,b,n,fun1);
}
else if(flag==2){
v=collect(a,b,n,fun2);
}
printf("%d\n",v);
return 0;
}
float collect(float s,float t,int n,float(*p)(float x)){
int i;
float f,h,x,y1,y2,area;
f=0.0;
h=(t-s)/n; //划分区间
x=s; //上底x
y1=(*p)(x); //上底长
for(i=1;i<=n;i++){
x=x+h; //下底x
y2=(*p)(x); //下底长
area=(y1+y2)*h/2;//梯形面积
y1=y2; //下底作为上底,计算下一个梯形面积
f=f+area; //累加梯形面积
}
return (f);
}
/*给出两种定义函数*/
float fun1(float x){
float fx;
fx=x*x-2.0*x+2.0;
return (fx);
}
float fun2(float x){
float fx;
fx=x*x*x+3.0*x*x-x+2.0;
return (fx);
}