Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Java Contradicting Itself?

Should I declare Math.round(1/2) in Java to be an int or a double? If both are fine, which is more correct?

Also, why is it that Eclipse is telling me Math.round(1/2) = 0.0, while Math.round(0.5) = 1.0 ?

Any help would be appreciated!

like image 817
Hannah P Avatar asked Sep 17 '11 23:09

Hannah P


2 Answers

The compiler starts by evaluating the expression 1/2. Both those numbers are integers, so it does integer math. In integers, 1 divided by 2 is 0. Then, it casts the 0 to a double in order to pass it to Math.round().

If you want a correct answer, you need to pass in doubles: you can do this by using 1.0/2.0 instead of 1/2.

like image 89
Walter Harley Avatar answered Nov 01 '22 23:11

Walter Harley


1/2 is 0, because it is an integer expression.

If you want the floating point value, say 1.0/2.0 (or just 1./2).

like image 6
Kerrek SB Avatar answered Nov 01 '22 23:11

Kerrek SB