2

我有一个递归函数,它将重复该函数,直到不满足 if 条件然后输出一个整数。但是,此函数之外需要整数的函数正在接收一个单位。我应该如何修改代码以返回 int?

count(r,c,1,0)

   def count(r: Int, c: Int, countR: Int, lalaCount: Int): Int = {
    if (countR < (r + 1)) count(r,c,countR + 1, lalaCount + countR)
    else (lalaCount + c + 1)
   }

这是整个程序

object hw1 {
  def pascal(c: Int, r: Int): Int = {

   count(r,c,1,0)

   def count(r: Int, c: Int, countR: Int, lalaCount: Int): Int = {
    if (countR < (r + 1)) count(r,c,countR + 1, lalaCount + countR)
    else (lalaCount + c + 1)
   }
  } //On this line eclipse is saying "Multiple markers at this line
    //- type mismatch;  found   : Unit  required: Int
    //- type mismatch;  found   : Unit  required: Int
pascal(3,4)

}

4

1 回答 1

6

从返回的值pascal是它包含的最后一个表达式。你希望它成为你的评价,count但这不是最后一件事。正如您所发现的,作业(def、val 等)属于 Unit 类型:

  def pascal(c: Int, r: Int): Int = {

   count(r,c,1,0) // => Int

   def count(r: Int, c: Int, countR: Int, lalaCount: Int): Int = {
    if (countR < (r + 1)) count(r,c,countR + 1, lalaCount + countR)
    else (lalaCount + c + 1)
   } // => Unit
  }

只需在count(r,c,1,0) 之后移动,def这应该可以解决问题。

于 2012-09-30T05:18:17.277 回答