一个用矩形法求定积分的通用程序。编译,连接均无问题,但运行结果为:floating point divided by 0.
程序如下: #include<math.h> #define E 1e-8 main() { double integral(float low,float up,double (*fun)()); double i_value; printf("\nThe integral of sin(x) from 0 to 1 is:\n"); i_value=integral(0,1,sin); printf("%.8f\n",i_value); printf("The integral of cos(x) from -1 to 1 is:\n"); i_value=integral(-1,1,cos); printf("%.8f\n",i_value); printf("The integral of exp(x) from 0 to 2 is:\n"); printf("%.8f\n",i_value); }
double integral(float low,float up,double (*fun)()) { double h,sum=0,intg1,intg2=0; int i,n=10; h=(up-low)/n; for(i=0;i<n;i++) sum+=(*fun)(low+i*h); intg1=sum*h; for(;fabs(intg2-intg1)>E;) { n*=2; h=(up-low)/n; for(sum=0,i=0;i<n;i++) sum+=(*fun)(low+i*h); intg2=sum*h; } return intg2; }