Groovy中的奇怪除法运算符

9
我是一个新手,对Groovy不太熟悉。
为什么这个在运行时会抛出异常:
int[] a = [1,2,3,4,5]
int lo=0
int hi=4

int x = a[(lo+hi)/2]
assert x == 3

虽然这些是可以的:

int x = a[(int)(lo+hi)/2]

并且

int i = (lo+hi)/2
int x = a[i]

请告诉我们异常情况。 - Andreas Dolk
groovy.lang.MissingMethodException: [I.getAt() 没有适用于参数类型为 (java.math.BigDecimal) values: [2] 的方法签名 可能的解决方案包括:getAt(groovy.lang.Range),getAt(java.lang.Integer),getAt(java.util.Collection),getAt(groovy.lang.ObjectRange),getAt(groovy.lang.IntRange),getAt(java.lang.String)。 - hint
1个回答

15

Groovy中,如果操作数是IntegerLongBigIntegerBigDecimal类型,则除法的结果为BigDecimal类型:

请参见此教程了解更多信息:

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;

5
所有数值类型都支持intdiv()方法,它允许您进行整数除法而无需进行强制转换,例如:assert 3.intdiv(2) == 1I - ataylor
这个常量“2”在这种情况下是什么类型的除数? - Alexander Stohr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接