gpt4 book ai didi

groovy - Groovy 中奇怪的除法运算符

转载 作者:行者123 更新时间:2023-12-02 03:19:21 29 4
gpt4 key购买 nike

我是 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]

最佳答案

在 groovy 中,如果操作数的类型为 IntegerLongBigInteger,则除法结果为 BigDecimalBigDecimal:

例如参见 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;

关于groovy - Groovy 中奇怪的除法运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5063332/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com