如何在C ++或VC ++中计算定积分?

时间:2014-11-18 18:39:58

标签: c++ visual-c++

我想用VC ++或C ++编写一个使用定积分的程序。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

有趣的是,我刚才讨论了这篇文章,解释了一种使用函数指针计算数值积分的方法。

https://helloacm.com/c-function-to-compute-numerical-integral-using-function-pointers/

像x ^ 2 * cos(x):

你需要一个重载的积分函数:

double integral(double(*f)(double x), double(*g)(double x, double y), double a, double b, int n)
{
    double step = (b - a)/n;   // width of rectangle
    double area = 0.0;
    double y = 0;  // height of rectangle

    for(int i = 0; i < n; ++i)
    {
        y = f(a + (i + 0.5) * step) * g(a + (i + 0.5) * step, y);
        area += y * step  // find the area of the rectangle and add it to the previous area. Effectively summing up the area under the curve.
    }

    return area;
}

致电:

int main()
{
    int x = 3;
    int low_end = 0;
    int high_end = 2 * M_PI;
    int steps = 100;
    cout << integral(std::powf, std::cosf, low_end, high_end, steps);
    return 0;
}