help with formula << output 0 ??

Hey guys! Very new to C++. Just started taking it this semester.
For some reason my output keeps coming out as [0.000] and I cannot figure out why. Can someone please help me?

** I also tried making r & h a double and it still came out as 0.

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

int main()
{

int r = 0;
int h = 0;
const double pi = 3.14159;

cout << "Enter radius: " << endl;
cin >> r;

cout << "Enter height: " << endl;
cin >> h;

double volume = (1/3) * pi * (r * r) * h;

cout << fixed << setprecision(3);
cout << "The volume of the cone is: [" << volume << "]";

return 0;
}

OUTPUT:
Enter radius:
5
Enter height:
10
The volume of the cone is: [0.000]
Last edited on
Change 1/3 to 1/3.0 because integer division gives 0 result

You can also use M_PI instead of defining your own.
https://stackoverflow.com/questions/1727881/how-to-use-the-pi-constant-in-c

double volume = M_PI/3.0 * (r * r) * h;
Last edited on
@cgill2

Replace line double volume = (1/3) * pi * (r * r) * h; with double volume = (1.0/3.0) * pi * (r * r) * h;

The problem you're having is you are using int in the division of 1/3, and that will be a 0, whereas 1.0/3.0, does not.

You may want to add a << endl; at the end of line cout << "The volume of the cone is: [" << volume << "]";. Mainly for looks.

oh okay! It worked! Also added the << endl;

Thanks so much!
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
#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{
    
    int r = 0;
    int h = 0;
    
    cout << "Enter radius: "; // INPUT ON ONE LINE IS SOMETIMES BEST
    cin >> r;
    
    cout << "Enter height: ";
    cin >> h;
    
    double volume = M_PI/3. * (r * r) * h;
    
    cout << fixed << setprecision(3);
    cout << "The volume of the cone is: [" << volume << "]\n";
    
    return 0;
}
Topic archived. No new replies allowed.