溫馨提示×

C++ numeric庫中的積分函數(shù)怎樣

c++
小樊
87
2024-07-30 11:52:06
欄目: 編程語言

在C++的numeric庫中,有一個(gè)std::integral函數(shù)可用于計(jì)算積分。該函數(shù)接受一個(gè)起始點(diǎn)、一個(gè)結(jié)束點(diǎn)和一個(gè)函數(shù)作為參數(shù),并返回積分結(jié)果。例如:

#include <iostream>
#include <numeric>
#include <cmath>

// 定義被積函數(shù)
double f(double x) {
    return x * x;
}

int main() {
    double a = 0.0; // 積分下限
    double b = 1.0; // 積分上限

    double result = std::integral(f, a, b); // 計(jì)算積分結(jié)果

    std::cout << "The integral of x^2 from 0 to 1 is: " << result << std::endl;

    return 0;
}

在上面的例子中,我們定義了一個(gè)函數(shù)f(x) = x^2,然后使用std::integral函數(shù)計(jì)算了該函數(shù)在區(qū)間[0,1]上的積分結(jié)果。輸出結(jié)果為"The integral of x^2 from 0 to 1 is: 0.333333"。

0