#include<iostream>
#include<cmath>
using namespace std;
//用矩形法求定积分的通用函数
//矩形法 定积分的几何定义
double func_sin(double x)
{
return sin(x);
}
double func_cos(double x)
{
return cos(x);
}
double func_ex(double x)
{
return exp(x);
}
double integral(double (*p)(double), double a, double b, int n)
{
double x, h, s=0;
h = (b - a) / n; //上限减下限 再等分成n份
x = a; //从下限开始,计算n个矩形的面积 最后累加
for (int i = 0; i < n; i++)
{
x = x + h; //底加一个单位(即之前分的平均长度)
s += (*p)(x) * h; //每个矩形的面积累加
}
return s;
}
int main() {
double a1, b1, a2, b2, a3, b3;
double (*p)(double); //指向函数的指针
cout << "input a1,b1:";
cin >> a1 >> b1;
cout << "input a2,b2:";
cin >> a2 >> b2;
cout << "input a3,b3:";
cin >> a3 >> b3;
p = func_sin;
cout << "the integral of sin(x) is :" << integral(p, a1, b1, 20) << endl;
p = func_cos;
cout << "the integral of cos(x) is :" << integral(p, a2, b2, 20) << endl;
p = func_ex;
cout << "the integral of exp(x) is :" << integral(p, a3, b3, 20) << endl;
system("pause");
return 0;
}
谭浩强c++第三版6-13
最新推荐文章于 2024-08-17 23:59:05 发布