答案不标准也不一定是最佳,仅供参考
#include <stdio.h>
#include <stdlib.h>
double TestFounc(double x)
{
return (x+1);
}
double TestFounc2(double x)
{
return x;
}
double DJF(double xStart,double xEnd,double (*Founc)(double x))//利用梯形近似求出函数曲线与X轴围成的面积
{
double y1,y2,RetValue=0,cur,dx;
dx=(xEnd-xStart)/65536;
y2=Founc(xStart);
for(cur=xStart+dx ; cur <= xEnd ; cur+=dx)
{
y1=y2;
y2=Founc(cur);
RetValue+=(y1+y2)*dx/2.0;
}
return RetValue;
}
void main()
{
double RetValue = DJF(2,4,TestFounc);
printf("测试函数y=x+1,XStart=2,XEnd=4积分结果:%lf/n",RetValue);
RetValue = DJF(-1,1,TestFounc2);
printf("测试函数y=x,XStart=-1,XEnd=1 积分结果:%lf/n",RetValue);
getchar();
}
完整内容所在目录:http://www.mythroad.net/tag/q_written_examination_and_interview_code_title/