我正在尝试找出此编译错误:
Error:(51, 4) identifier expected but '}' found.
} else if (n < 0) {
^
对于此代码:
def nthPowerOfX(n: Int, x:Double) : Double = {
if (n == 0) {
1.0
} else if (n < 0) {
1.0 / nthPowerOfX(n,x)
} else if (n % 2 == 0 && n > 0) {
nthPowerOfX(2, nthPowerOfX(n/2,x))
} else {
x*nthPowerOfX(n-1, x)
}
}
我也尝试了返回语句,但这对我的理解也不重要。
jozef是正确的!没有错误。请考虑使用此信息:
def nthPowerOfX(n: Int, x:Double) : Double = {
n match{
case 0 => 1.0
case x if x < 0 => 1.0 / nthPowerOfX(n,x)
case x if x % 2 == 0 && x > 0 => nthPowerOfX(2, nthPowerOfX(n/2,x))
case x => x*nthPowerOfX(n-1, x)
}
}
但请记住,递归是危险的,最好使用尾部递归,如果我们谈论的是Scala。