方法mod或%的Groovy错误
我刚开始用Groovy编程,我遇到了这个错误,我想看看是否有人能帮我解决这个问题方法mod或%的Groovy错误,groovy,sequence,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)
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”似乎被强制转换为一个大十进制
num=num/2
如果将冰雹方法的签名更改为:
def hailstone(int-num)
它不会崩溃(因为参数在每次调用时都会强制为int),但这可能不会给出您想要的结果,因为您将失去精度,例如,当'num'是奇数,而num/2产生一个十进制值时,该值将被截断
有关Groovy数学操作工作方式(有时令人惊讶)的更多信息,请查看运行此代码后,由于findAll,它没有生成正确的输出。下面是一些小改动的代码:
def list = [1,2,3].collect { hailstone(it) } // use collect, no need for the "it ->" variable it is implicit.
def hailstone(int num) { // int data type to prevent BigDecimal from being passed to mod()
if (num == 1) {
return 1 // no need for semi-colons in groovy
} else if (num % 2 == 0) { // use modulus operator
num = num / 2
} else {
num = 3 * num + 1
}
return 1 + hailstone(num) // this line happens regardless of the condition in the else if or the else
}
println list // outputs : [1,2,8]