C语言用矩形法,梯形法计算定积分
要求:写一个通用的函数实现,用指向函数的指针实现,用矩形法和梯形法计算定积分,断点分11,101,1001三种情况计算,并比较计算结果
#include <stdio.h>
#include <math.h>
#define PI 3.1415926
#define E 2.71828182
double my_tan(double x)
{
return tan(x);
}
double my_exp(double x)
{
return exp(x);
}
double fun1(int point,double a,double b,double (*p)(double))
{
double sum=0,n=fabs(a-b)/point;
int i=0;
for(i=0;i<point;i++)
{
sum+=n*(*p)(a+i*n+n/2);
}
return sum;
}
double fun2(int point,double a,double b,double (*p)(double))
{
double sum=0,n=fabs(a-b)/point;
int i=0,j=0;
for(i=0;i<point;i++)
{
sum+=n*((*p)(a+n*j)+(*p)(a+n*(j+1)))/2.0;
j+=1;
}
return sum;
}
void menu()
{
printf("************************************\n");
printf("***** 1.矩形法 2.梯形法 ********\n");
printf("************************************\n");
}
int main()
{
double tValue1,tValue2,tValue3,eValue1,eValue2,eValue3;
int k;
printf("你想要用什么方法计算定积分!!!\n");
menu();
printf("请输入:>");
scanf("%d",&k);
switch(k)
{
case 1:
{
tValue1=fun1(11,-PI/4,PI/4,my_tan);
tValue2=fun1(101,-PI/4,PI/4,my_tan);
tValue3=fun1(1001,-PI/4,PI/4,my_tan);
eValue1=fun1(11,-E,E,my_exp);
eValue2=fun1(101,-E,E,my_exp);
eValue3=fun1(1001,-E,E,my_exp);
break;
}
case 2:
{
tValue1=fun2(11,-PI/4,PI/4,my_tan);
tValue2=fun2(101,-PI/4,PI/4,my_tan);
tValue3=fun2(1001,-PI/4,PI/4,my_tan);
eValue1=fun2(11,-E,E,my_exp);
eValue2=fun2(101,-E,E,my_exp);
eValue3=fun2(1001,-E,E,my_exp);
break;
}
default:
printf("输入错误\n");
goto end;
break;
}
printf("tValue1=%f\ntValue2=%f\ntValue3=%f\n",tValue1,tValue2,tValue3);
printf("eValue1=%f\neValue2=%f\neValue3=%f\n",eValue1,eValue2,eValue3);
end:
return 0;
}
|