1 //这里f()为被积函数,输入a,b为积分上下限, 2 //eps为计算精度[这里要注意假收敛,一般设小一点好] 3 #include4 #include 5 #define eps 1e-6 6 using namespace std; 7 double f(double x){ 8 return sqrt(1+cos(x)*cos(x)); 9 }//被积函数10 double Sn(double a,double b,double n){11 double h=(a+b)/(2*n);12 double sum=0;13 for(int k=1;k<=n;k++){14 sum+=2*f(a+(2*k-1)*h);15 sum+=f(a+2*k*h);16 }17 sum=(sum*2+f(a)-f(b))*h/3;18 return sum;19 }//辛普森公式20 double Solve(double a,double b){21 int i=1;22 double S1n=Sn(a,b,i);23 double S2n=Sn(a,b,2*i);24 while(fabs(S1n-S2n)>eps){25 cout<<"n = "< <<" S1 = "< <<" S2 = "< <<'\n';26 i++;27 S1n=S2n;28 S2n=Sn(a,b,2*i);29 }30 return S2n;31 }32 int main(){33 cout< <<'\n';34 }