1
volume = (4/3 * PI) * (Math.Pow(5, 3));
return volume;

The code above should return 523.6 but it returns 392.7. I can't figure it out but its probably something stupid that I am missing. Changing it to be a double literal does not change the problem.

3 Answers3

5

4 and 3 are both ints so dividing them will produce an int, 1. This is probably not the value you were expecting.

You have to cast the 4 to a double before computing the quotient with 3.

inavda
  • 333
  • 5
  • 15
1

You can also just change 4 to 4.0, since yes the issue is that it is a integer so something called Integer Division happens.

volume = (4.0/3.0 * PI) * (Math.Pow(5, 3));
return volume;
cheriejw
  • 364
  • 3
  • 13
-5

cast to double

double volume = (4.0 / 3.0 * Math.PI) * (Math.Pow(5, 3));
Hamid Jolany
  • 800
  • 7
  • 11
  • 4
    This experiences the same problem because it calculates `4 / 3` using integer division. https://www.ideone.com/nyu3Xt – clcto Oct 11 '18 at 22:11