A. write pseudocode algorithm to determine the integral of a function between two specified points using the rectangular rule. B. write C++ computer programs to determine the integral of a function between two specified points using the rectangular rule
#include <iostream>
#include <cmath>
using namespace std;
/*
* f - pointer to function,
* a,b - borders, where a < b,
* n - number of rectangles.
*/
double integrate(double (*f)(double), double a, double b, int n)
{
double x, y, area = 0.0;
/* h - step */
double h = (b - a) / n;
for (int i = 0; i < n; i++) {
x = a + i * h;
y = a + (i + 1) * h;
area += h * f(0.5 * (x + y));
}
return area;
}
int main()
{
auto func = [](double x) {
return sin(x) + cos(x);
};
cout << "integrate: sin(x) + cos(x)\n";
double a, b;
int n;
cout << "lower_bound(a): ";
cin >> a;
cout << "upper_bound(b): ";
cin >> b;
cout << "number_of_reactangles: ";
cin >> n;
cout << "I=" << integrate(func, a, b, n);
return 0;
}
Comments
Leave a comment