#include<iostream>#include<cmath>#include<functional>usingnamespace std;// 定积分函数doubleintegrate(function<double(double)> func,double a,double b,int num_intervals){double h =(b - a)/ num_intervals;// 计算每个小区间的宽度double result =(func(a)+func(b))/2.0;// 初始化结果为端点的函数值之和的一半// 使用梯形法则进行数值积分for(int i =1; i < num_intervals;++i){double x = a + i * h;
result +=func(x);}
result *= h;// 乘以小区间宽度得到最终结果return result;}// 要积分的函数doubleFunc1(double x){return x +2- x * x;}doubleFunc2(double x){returnsqrt(1- x * x)+ x;}doubleFunc3(double x){double tmp =(4- x * x);returnsqrt(tmp * tmp * tmp);}doubleFunc4(double x){returnsin(x);}
function<double(double)>ReturnFunc(int op){if(op ==1)return Func1;elseif(op ==2)return Func2;elseif(op ==3)return Func3;elsereturn Func4;}intmain(){int num_intervals =1000;int op;double a, b;while(cin >> op >> a >> b){auto f =ReturnFunc(op);double result =integrate(f, a, b, num_intervals);if(op !=4)printf("∫[%.2lf~%.2lf]f%d(x)dx=%.2lf\n", a, b, op, result);else{printf("∫[%.2lf~%.2lf]sin(x)dx=%.2lf\n", a, b, result);}}return0;}