Mutiplication in C++

Viewed 49

So I was doing an easy problem to calculate the volume of a sphere which is 4/3 * PI * R³ (R= radius of it)

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main() {


    double R, pi = 3.14159, volume = 0;

    cin >> R;

    volume = 4/3 * pi * R * R * R;

    std::cout << std::fixed << std::setprecision(3) << "VOLUME = " << volume << endl;

    return 0;
}

I've noticed that it gives me the wrong answer but when I change the calculation of volume to:

volume = R * R * R * pi * 4/3;

It does give me the right answer. So... Why? Am I doing something wrong here?

1 Answers

I believe your problem is here:

volume = 4/3*pi*R*R*R;

In particular 4/3 is dividing integer 4 by integer 3, which results in an integer result of 1; probably not what you intended. I think you want this instead:

volume = 4./3.*pi*R*R*R;

(note the periods; that tells C++ that the values should be double-precision floats rather than integers, so you won't get the massive rounding error)

Related