矩形法求积分sin cos exp
矩形法求积分就是按照积分的定义将被积函数的积分区域分成很多个小矩形,然后累加求和的过程
代码如下:
1 // 矩形法求sinx cosx exp(x) 的积分 2 # include<stdio.h> 3 # include<math.h> 4 double a,b,c; 5 int n=20,d;//积分区域被分成n个小矩形 6 int main() 7 { 8 double (*p)(double); 9 double integral(double(*)(double),double,double,int); 10 //float fsin(float); 11 //float fcos(float); 12 //float fexp(float); 13 scanf("%lf%lf%d",&a,&b,&d); //开始错在这里,double型输入应该为%lf 14 if(d==1) p=sin; 15 else if(d==2) p=cos; 16 else if(d==3) p=exp; 17 else 18 { 19 printf("选择错误\n"); 20 return 0; 21 } 22 c=integral(p,a,b,n); 23 printf("%7.4f\n",c); 24 return 0; 25 } 26 27 double integral(double(*p)(double),double a,double b,int n) 28 { 29 int i; 30 double h,d,s=0; 31 d=(b-a)/n; 32 h=a; 33 for(i=0;i<n;i++) 34 { 35 h=h+d; 36 s=s+p(h)*d; 37 } 38 return s; 39 } 40 41 /*float fsin(float x) 42 { 43 return sin(x); 44 } 45 46 float fcos(float x) 47 { 48 return cos(x); 49 } 50 51 float fexp(float x) 52 { 53 return exp(x); 54 }*/