C++ area under a curve for equation F(X) = 5x^3 + 7x^2 -3x+4; from 2 to 7 until
ID: 3664693 • Letter: C
Question
C++ area under a curve
for equation
F(X) = 5x^3 + 7x^2 -3x+4;
from 2 to 7
until the difference between the last two calculations is less than .0001
Why doesnt this code work?
// Source File: test.cpp
// Description: calculating the area under the curve
#include <iostream>
#include <cmath>
#include <math.h> //pow
using namespace std;
int main(){
double A = 0;
double B = 0;
double Area = 0;
double height =0;
double width = 0;
double current_total = 0;
double previous_total =0;
A = 2;
B = 7;
double n =10;
double xpos = 0;
double diff=1;
double prev_width = 0;
double prev_n =0;
do{
//current total
width = (B - A)/n;
for(double i =0; i<n; i++){
// F(X) = 5x^3 + 7x^2 -3x+4;
xpos = A + width*i;
height = 5*pow(xpos, 3) + 7* pow(xpos, 2) - 3*xpos + 4;
Area = height * width;
current_total = Area + current_total;
}
//previous total
prev_width = (B - A)/(n-1);
prev_n = n-1;
for(double i =0; i<prev_n; i++){
// F(X) = 5x^3 + 7x^2 -3x+4;
xpos = A + prev_width*i;
height = 5*pow(xpos, 3) + 7* pow(xpos, 2) - 3*xpos + 4;
Area = height * prev_width;
previous_total = Area + previous_total;
}
diff = current_total - previous_total ;
n++;
}while ( diff > 0.0001);
cout << "Result: " << current_total << endl;
return 0;
}
Explanation / Answer
SOlution:
#include <iostream>
#include <cmath>
#include <math.h> //pow
using namespace std;
int main()
{
double A = 0;
double B = 0;
double Area = 0;
double height =0;
double width = 0;
double current_total = 0;
double previous_total =0;
A = 2;
B = 7;
double n =10;
double xpos = 0;
double diff=1;
double prev_width = 0;
double prev_n =0;
do{
//current total
width = (B - A)/n;
for(double i =0; i<n; i++){
// F(X) = 5x^3 + 7x^2 -3x+4;
xpos = A + width*i;
height = 5*pow(xpos, 3) + 7* pow(xpos, 2) - 3*xpos + 4;
Area = height * width;
current_total = Area + current_total;
}
//previous total
prev_width = (B - A)/(n-1);
prev_n = n-1;
for(double i =0; i<prev_n; i++){
// F(X) = 5x^3 + 7x^2 -3x+4;
xpos = A + prev_width*i;
height = 5*pow(xpos, 3) + 7* pow(xpos, 2) - 3*xpos + 4;
Area = height * prev_width;
previous_total = Area + previous_total;
}
diff = current_total - previous_total ;
n++;
} while ( diff < 0.0001);
cout << "Result: " << current_total << endl;
return 0;
}
Sample Run:
Result: 3237.19
The Mistake is line :
} while ( diff > 0.0001);
It should be
} while ( diff < 0.0001);
as you said " the difference between the last two calculations is less than .0001"
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.