Can someone explain to me why the result of the codes below is different? Thanks in advance. All the variables are double.
First:
volume=(4/3)*(Math.PI*Math.pow(raio,3))
if I declare that raio=5, the result will be=392,xxx
The result will also be 392 if:
volume=(Math.PI*Math.pow(raio,3))*(4/3);
Second:
volume=(Math.PI*Math.pow(raio,3))*4/3;
if I declare that raio=5, the result will now be correct: 523,xxx
It's because when you use:
volume=(Math.PI*Math.pow(raio,3))*(4/3);
What happens is (4/3) is evaluated as integer division, so (4/3) = 1.
Thus,
volume=(Math.PI*Math.pow(raio,3))*4/3;
would work because it's a double * 4, which is a double, then divided by 3, which is also a double.
If you try this:
volume=(Math.PI*Math.pow(raio,3))*(4.0/3.0);
You should see it work.
Note that you probably can get away with just 4.0/3 or just 4/3.0 .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With