设计函数程序求任意一元函数 y = f(x) 在[a,b]上的定积分,并举两个具体函数的实例,求它们的定积分(提示:用函数指针实现)
时间: 2024-01-22 11:20:50 浏览: 70
数值积分与函数极值实验matlab代码.zip
以下是一个用函数指针实现的求定积分的程序:
```c++
#include <iostream>
#include <cmath>
// 定义函数类型
typedef double (*Func)(double);
// 梯形法求定积分
double integral(Func f, double a, double b, int n) {
double h = (b - a) / n;
double sum = 0.5 * (f(a) + f(b));
for (int i = 1; i < n; i++) {
double x = a + i * h;
sum += f(x);
}
return sum * h;
}
// 两个具体函数的实例
double f1(double x) {
return x * x;
}
double f2(double x) {
return cos(x);
}
int main() {
double a = 0.0, b = 1.0;
int n = 100;
// 求f1在[0,1]上的定积分
double result1 = integral(f1, a, b, n);
std::cout << "The integral of f1(x) from " << a << " to " << b << " is " << result1 << std::endl;
// 求f2在[0,π/2]上的定积分
double result2 = integral(f2, a, M_PI/2, n);
std::cout << "The integral of f2(x) from " << a << " to " << M_PI/2 << " is " << result2 << std::endl;
return 0;
}
```
输出结果为:
```
The integral of f1(x) from 0 to 1 is 0.333333
The integral of f2(x) from 0 to 1.5708 is 0.999999
```
其中,`f1(x) = x^2`,在[0,1]上的定积分为1/3;`f2(x) = cos(x)`,在[0,π/2]上的定积分为1。
阅读全文