Search code examples
c++cmath

How to stop c++ from rounding to closest integer


I'm doing an area of a cylinder calculator and for some reason, c++ is rounding to the nearest number , here's my code:

int volume()
{
    int radius;
    int height;
    double long volume;
    double pi;
    pi = 3.14;
    cout << "Enter Radius: ";
    cin >> radius;
    cout << "Enter height: ";
    cin >> height;
    volume = radius * radius * height * pi;
    return volume;
}
int main()
{
    cout << "Formula Calculator \n";
    cout << "The volume  is " << volume();
    return 0;
}

It always rounds the answer to the nearest integer pls help :(


Solution

  • double long volume()
    {
        int radius;           //Radius of a cylinder
        int height;           //Height of a cylinder
        double long volume;   //The resulting volume of the cylinder
        double pi = 3.14;     //The constant pi
    
        cout << "Enter Radius: ";
        cin >> radius;        //User inputs radius of cylinder
        cout << "Enter height: ";
        cin >> height;        //User inputs height of cylinder
        volume = radius *  radius * height * pi ; // v = (pi)(h)(r)^2
    
        return volume;
    }
    int main ()
    {
        cout << "Formula Calculator \n";
        cout << "The volume  is " << volume();
    
        return 0;
    }
    

    The only issue I found was with the declaration of your function. You used int instead of double long that you used to declare your resulting volume. Also remove the c from cvolume() in your main function.