0

I was calculating the volume of a sphere and after tons of research I found that I cannot use:

float sphereRadius = 2.33;
float volSphere = 0;
volSphere = (4/3) * (M_PI) * std::pow(sphereRadius, 3);

But must add the 3.0 instead to get the right answer.

volSphere = (4/3.0) * (M_PI) * std::pow(sphereRadius, 3);

Why must a decimal be added to get the correct calculation?

Blaze
  • 16,736
  • 2
  • 25
  • 44
Michael Rader
  • 5,839
  • 8
  • 33
  • 43

1 Answers1

2

(4/3) is one integer divided by another integer, which results in another integer. An integer can't be 1.33 or anything like that, so it gets truncated to 1. With the decimal, you're telling it to be a double instead, and dividing an integer by a double results in a double, which supports fractions.

Blaze
  • 16,736
  • 2
  • 25
  • 44
  • s/rounded/truncated/ ;) – Quentin Oct 18 '18 at 08:45
  • Haha yep, "truncated" is indeed the correct term here. "rounded" could be misunderstood... it never actually rounds up positive numbers. Thanks for the hint, I added it to the answer. – Blaze Oct 18 '18 at 08:50