Search code examples
c++c++11mathvolume

Multiplication/division order(?) confusion


I'm just calculating the volume of the sphere and unexpectedly

  volume = (4/3)*M_PI*pow(radius, 3);
or
  volume = 4/3*M_PI*pow(radius, 3);

gives 392.699 (should be 523.6)

But if I write

volume = 4*M_PI/3*pow(radius, 3);

or

M_PI*4/3*pow(radius_, 3);

Everything is fine. But

M_PI*(4/3)*pow(radius_, 3);

again gives wrong result. I completely have no idea why it's happening so.. Probably I wrote the wrong title, but I just don't understand what's going wrong here..


Solution

  • 4/3 will return 1 in c++, since both 4 and 3 are integers, and dividing two integers will result in integer division. You can solve this by performing floating-point division: 4.0/3.0. This will give the expected output.

    The reason volume = 4*M_PI/3*pow(radius, 3); works, is because multiplying an integer by a double, returns a double. Since M_PI is a double, you get the expected output.