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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
/*-----------------------------------------------------------------*/
/* Program chapter6_12 */
/* */
/* This program estimates the area under a given curve */
/* using trapezoids with equal bases. */
#include<iostream> //Required for cin, cout
#include<cmath> //Required for exp()
using namespace std;
// Function prototypes.
double integrate(double a, double b, int n);
double f(double x);
int main()
{
// Declare objects
int num_trapezoids;
double a, b, area,k;
// Get input from user.
cout << "Enter the interval endpoints, a and b\n";
cin >> a >> b;
cout << "Enter the number of trapezoids\n";
cin >> num_trapezoids; //Starting with 5
// Estimate area under the curve of 2ln(3x)
area = integrate(a, b, num_trapezoids);
for (k = 1; k <= 4; k = k + 1)
{ //How many times we want it to ask
cout << "Enter the number of trapezoids again x 10." << endl;
cin >> num_trapezoids;
}
// Print result.
cout << "Using " << num_trapezoids
<< " trapezoids, the estimated area is "
<< area << endl;
return 0;
}
/*-----------------------------------------------------------------*/
/*-----------------------------------------------------------------*/
double integrate(double a, double b, int n)
{
// Declare objects.
double sum(0), x, base, area;
base = (b-a)/n;
for(int k=2; k<=n; k++)
{
x = a + base*(k-1);
sum = sum + f(x);
}
area = 0.5*base*(f(a) + 2*sum + f(b));
return area;
}
double f(double x)
{
return(2*log(3*x));
}
/*-----------------------------------------------------------------*/
|