Hello, I am new to C++ so try to not be too hard on me. I have been searching the forums and google for a few hours to try and figure this out. I am trying to calculate the area and volume of a cone from 10-20 with a step increment of 0.5 with a while loop and I cannot figure out why my calculations are correct, but the numbers are not matching up. I have tried setting r and h to r=r=.5; and h the same, but it will not compute. There are helpful articles for the for loop, but not while.
It is setting the correct calculations for 10 on 11's column and I have tried setting int r=9, but the calculations are not matching up.
usingnamespace std;
/*
*
*/
int main(int argc, char** argv)
{
constdouble PI =3.14159265359;
int h=10; //height
int r=10; //radius
double area=0.0;
double volume=0.0;
cout<<"The program calculates the area and volume of a cone from 10-20"<<endl;
cout<<"in 0.5 increments."<<endl;
cout<<" "<<endl;
cout<<" Radius Area Volume"<<endl;
cout<<fixed<<setprecision(0);
//while loop
while (r<=20)
{
//area of a cone
area= PI*r*(r+sqrt(h*h+r*r));
//volume of a cone
volume = PI*r*r*(h/3.0);
r++;
h++;
cout<<setw(4)<<r<<setw(14)<<setprecision(2)<<area<<setw(12)<<volume<<endl;
}
return 0;
}
Output:
The program calculates the area and volume of a cone from 10-20
in 0.5 increments.
h and r need to be floating point (double) if you want to increment them by 0.5, and the increment should occur after you print a line of the table. So maybe something like this:
#include <iostream>
#include <iomanip>
#include <math.h>
usingnamespace std;
int main() {
constdouble PI = 3.14159265359;
double h = 10.0; //height
double r = 10.0; //radius
double area = 0.0;
double volume = 0.0;
cout << "The program calculates the area and volume of a cone";
cout << "from 10-20 in 0.5 increments.\n\n";
cout << "Radius Area Volume\n";
cout << fixed;
while (r <= 20) {
//area of a cone
area= PI * r * (r + sqrt(h * h + r * r));
//volume of a cone
volume = PI * r * r * h / 3.0;
cout << setprecision(1) << setw( 4) << r << ' '
<< setprecision(2) << setw(14) << area << ' '
<< setw(12) << volume << '\n';
r += 0.5;
h += 0.5;
}
}
Thank you so much for the fast reply. The teacher gave us some sample code to use on the assignment and it was not helpful at all on increasing increments in a while loop and online most of what i could find was for for loops. Appreciate it so much.
The program calculates the area and volume of a cone from 10-20
in 0.5 increments.