方法mod或%的Groovy错误

Nei*_*ill 5 groovy sequence

我刚刚开始在Groovy中编程,我遇到了这个错误,我想知道是否有人可以帮助我解决这个问题.

java.lang.UnsupportedOperationException: Cannot use mod() on this number type: java.math.BigDecimal with value: 5
    at Script1.hailstone(Script1.groovy:8)
    at Script1$hailstone.callCurrent(Unknown Source)
    at Script1.hailstone(Script1.groovy:11)
    at Script1$hailstone.callCurrent(Unknown Source)
    at Script1.hailstone(Script1.groovy:14)
    at Script1$_run_closure1.doCall(Script1.groovy:1)
    at Script1.run(Script1.groovy:1)
Run Code Online (Sandbox Code Playgroud)

我有以下Groovy代码

def list = [1,2,3].findAll{it-> hailstone(it)}

def hailstone(num){
    if(num==1){
        return 1;
    }
    println num
    println num.mod(2)
    if(num.mod(2)==0){
        num = num/2;
        return 1 + hailstone(num)
    }else{
        num = 3*num + 1
        return 1 + hailstone(num)
    }
}
Run Code Online (Sandbox Code Playgroud)

​ ​

和输出:

2
0
3
1 
10
0
5
Run Code Online (Sandbox Code Playgroud)

然后它突然在5.mod(2)上抛出一个错误.

提前致谢.

Gre*_*eek 3

当你到达该行时,看起来“num”被强制转换为 BigDecimal num = num/2

如果将雹石方法的签名更改为: def hailstone(int num)它不会崩溃(因为参数将在每次调用时强制转换为 int),但这可能不会给出您想要的结果,因为您将失去精度,例如当 ' num' 是奇数,num/2 生成十进制值,该值将被截断。

有关 Groovy 数学运算工作方式(有时令人惊讶)的更多信息,请查看http://groovy.codehaus.org/Groovy+Math