我正在试图弄清楚这个编译错误:
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)
}
}
我也尝试过回复陈述,但这对我的理解没有帮助,也不重要。
答案 0 :(得分:0)
约瑟夫是对的!没有错误。请考虑使用此:
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,最好使用尾递归。