【问题标题】:Scala Error: identifier expected but '}' foundScala 错误:需要标识符,但找到了“}”
【发布时间】:2017-03-09 16:26:43
【问题描述】:

我正在尝试找出这个编译错误:

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)
  }
}

我也尝试过 return 语句,但这没有帮助,对我的理解也不重要。

【问题讨论】:

  • 您的 sn-p 中没有语法错误,可能在您的代码的其他部分。还可以考虑使用模式匹配而不是if else

标签: scala


【解决方案1】:

约瑟夫是对的!没有错误。请考虑使用这个:

  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,最好使用尾递归。

【讨论】:

    猜你喜欢
    • 2023-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多