Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - what's the difference between 2 little codes

Tags:

java

math

output

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

like image 770
Ricardo Almeida Avatar asked Jul 10 '26 07:07

Ricardo Almeida


1 Answers

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 .

like image 64
Plasmarob Avatar answered Jul 14 '26 13:07

Plasmarob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!