0

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..

SimpleAsk
  • 73
  • 5
  • 1
    debugging arithmetic expressions is simpler when you split them up in several steps. I'd suggest you to start with `auto factor = 4/3;` and see if that is what you expect – 463035818_is_not_an_ai May 05 '20 at 20:41
  • Starting with 4*M_PI, because M_PI is a floating pt number the result is too. Then subsequent results are. So, 4*M_PI/3 is all done as floating point. – QuentinUK May 05 '20 at 20:44

1 Answers1

5

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.

Azam Bham
  • 1,389
  • 5
  • 6
  • " and dividing two integers returns an integer" to be frankly this is inaccurate explanation. In this case it is more important what kind of division is performed, rather than what type it returns. Based on your explanation OP may think that casting result to floating point may help. – Slava May 05 '20 at 20:49