方法mod或%的Groovy错误

方法mod或%的Groovy错误,第1张

概述我刚刚开始在Groovy中编程,我遇到了这个错误,我想知道是否有人可以帮助我解决这个问题. java.lang.UnsupportedOperationException: Cannot use mod() on this number type: java.math.BigDecimal with value: 5 at Script1.hailstone(Script1.groovy: 我刚刚开始在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)    }}

和输出:

2031 1005

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

提前致谢.

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

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

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

总结

以上是内存溢出为你收集整理的方法mod或%的Groovy错误全部内容,希望文章能够帮你解决方法mod或%的Groovy错误所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1231510.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存