1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
#include <iostream>
int main(){
double a, b, h, sum = 0.;
double x1, x2, median;
double area;
int n;
std::cout << "Enter the ends of the interval [a, b] : \n";
std::cout << "a = ";
std::cin >> a;
std::cout << "b = ";
std::cin >> b;
if(b < a) return 1;
std::cout << "Number of subintervals of [a, b]? ";
std::cin >> n;
// The length of a subinterval
h = (b - a) / n;
for(int i = 0; i < n; ++i){
x1 = a + i * h; // abscissa of the left end
x2 = x1 + h; // abscissa of the right end
// For the function f(x) = x^2 we have
median = (x1 * x1 + x2 * x2) * .5;
// The area of each trapezoid
area = median * h;
// The area under the curve
sum += area;
}
std::cout << "Approx. area = " << sum << '\n';
std::cout << "Exact area = " << (b * b * b - a * a * a) / 3. << '\n';
return 0;
}
|
Example 1
**********
Enter the ends of the interval [a, b] :
a = 0
b = 4
Number of subintervals of [a, b]? 10
Approx. area = 21.44
Exact area = 21.3333
Example 2
**********
Enter the ends of the interval [a, b] :
a = 0
b = 4
Number of subintervals of [a, b]? 100
Approx. area = 21.3344
Exact area = 21.3333
Example 3
**********
Enter the ends of the interval [a, b] :
a = 0
b = 4
Number of subintervals of [a, b]? 1000
Approx. area = 21.3333
Exact area = 21.3333 |