加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

方法mod或%的Groovy错误

发布时间:2020-12-14 16:28:03 所属栏目:大数据 来源:网络整理
导读:我刚刚开始在Groovy中编程,我遇到了这个错误,我想知道是否有人可以帮助我解决这个问题. java.lang.UnsupportedOperationException: Cannot use mod() on this number type: java.math.BigDecimal with value: 5 at Script1.hailstone(Script1.groovy:8) at S
我刚刚开始在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)

我有以下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)
    }
}

和输出:

2
0
3
1 
10
0
5

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

提前致谢.

解决方法

当你点击线路时,看起来’num’被强制进入BigDecimal
num = num / 2

如果您将hailstone方法的签名更改为:
def hailstone(int num)它不会崩溃(因为参数将在每次调用时被强制转换为int),但这可能无法提供您想要的结果,因为您将失去精度,例如当’num’是一个奇数,而num / 2产生一个十进制值时,该值将被截断.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读