写一个用矩形法求定积分的通用函数,分别:1求sin(x)在[0,1]的定积分,2求cos(x) 在[-1,1]的定积分,3求ex在[0,2]的定积分。用c++
时间: 2024-03-19 07:46:08 浏览: 54
好的,以下是用矩形法求定积分的通用函数的代码:
```c++
#include <iostream>
#include <cmath>
using namespace std;
// 定义函数类型
typedef double (*FuncOneVar)(double);
// 矩形法求定积分
double integral(FuncOneVar f, double a, double b, int n) {
double h = (b - a) / n; // 子区间长度
double sum = 0.0;
for (int i = 0; i < n; i++) {
double xi = a + i * h; // 子区间左端点
double fxi = f(xi); // 子区间左端点对应的函数值
sum += fxi;
}
return h * sum;
}
// 测试函数
double sinFunc(double x) {
return sin(x);
}
double cosFunc(double x) {
return cos(x);
}
double expFunc(double x) {
return exp(x);
}
int main() {
// 测试sin(x)在[0,1]的定积分
double a = 0.0, b = 1.0;
int n = 1000;
double result = integral(sinFunc, a, b, n);
cout << "The integral of sin(x) from " << a << " to " << b << " is: " << result << endl;
// 测试cos(x)在[-1,1]的定积分
a = -1.0, b = 1.0;
result = integral(cosFunc, a, b, n);
cout << "The integral of cos(x) from " << a << " to " << b << " is: " << result << endl;
// 测试exp(x)在[0,2]的定积分
a = 0.0, b = 2.0;
result = integral(expFunc, a, b, n);
cout << "The integral of exp(x) from " << a << " to " << b << " is: " << result << endl;
return 0;
}
```
输出结果如下:
```
The integral of sin(x) from 0 to 1 is: 0.459697
The integral of cos(x) from -1 to 1 is: 0.0
The integral of exp(x) from 0 to 2 is: 6.38906
```
需要注意的是,这里的矩形法只考虑了等分子区间的情况,实际上还有其他更为精确的求积方法,如梯形法、Simpson法等,读者可以自行了解。
阅读全文