将ch4_9.cpp的程序改写为主函数调用integral()函数的形式,以求积分值
时间: 2024-05-15 14:16:57 浏览: 8
修改后的程序如下:
```c++
#include <iostream>
#include <cmath>
using namespace std;
double integral(double a, double b, int n) {
double h = (b - a) / n;
double sum = 0;
for (int i = 0; i < n; i++) {
double x = a + h * (i + 0.5);
sum += sin(x);
}
return h * sum;
}
int main() {
double a, b;
int n;
cout << "Enter the lower limit of integration: ";
cin >> a;
cout << "Enter the upper limit of integration: ";
cin >> b;
cout << "Enter the number of subintervals: ";
cin >> n;
double result = integral(a, b, n);
cout << "The result of the integration is " << result << endl;
return 0;
}
```
在主函数中调用了integral()函数,并将计算结果存储在result变量中,最后输出结果。