二分法梯形公式求积分
#include <iostream> #include <iomanip> #include <math.h> using namespace std; //二分梯形积分 //本函数用来求sinx/x在(0,1)区间的积分 long double f(double l) { return sin(l) / l; } long double Tn(double a, double b, long double xy) {//变步长梯形法 cout << " 二分次数 积分结果" << endl; long double S, T1, T2,m;//m指实际截断误差 double h,x;//步长 int k;//二分次数 T1 = (1 + f(b)) / 2; h = b - a; k = 0; do { cout << " " << k << " " << fixed << setprecision(10) << T1 << endl; S = 0; x = a + h / 2;//第一个要加的数 while (x < b) { S = S + f(x); x = x + h; } T2 = T1 / 2 + S * h / 2; m = (T2 - T1)*(T2 - T1); h = h / 2; T1 = T2; k++; } while (m >= xy * xy); cout << " " << k << " " << fixed << setprecision(10) << T1 << endl; return T2; } int main() { cout << "(〃'▽'〃)***!!!这是一个求函数f(x)积分的区间!!!***φ(>ω<*) " << endl; double a, b; long double xy,y; cout << "请依次输入带积分函数的积分区间" << endl; cout << "左区间:"; cin >> a; cout << "右区间:"; cin >> b; cout << "请输入函数结果所允许的最大误差:"; cin >> xy; cout << endl; y = Tn(a, b, xy); cout << "最后的结果为" << y << endl; cout << "******小王最棒!******" << endl; return 0; }
调试结果: