I am new to Groovy.
why this throws exception on runtime:
int[] a = [1,2,3,4,5]
int lo=0
int hi=4
int x = a[(lo+hi)/2]
assert x == 3
while these are ok:
int x = a[(int)(lo+hi)/2]
and
int i = (lo+hi)/2
int x = a[i]
In groovy a division results in a BigDecimal
if the operands are of type Integer
, Long
, BigInteger
or BigDecimal
:
See for instance this tutorial:
The division operators "/" and "/=" produce a Double result if either operand is either Float or Double and a BigDecimal result otherwise (both operands are any combination of Integer, Long, BigInteger, or BigDecimal).
[...]
For example
1/2 == new java.math.BigDecimal("0.5");
[...]
Integer division can be performed on the integral types by casting the result of the division. For example:
assert (int)(3/2) == 1I;
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