gpt4 book ai didi

scala - 递归函数不返回 Int

转载 作者:行者123 更新时间:2023-12-03 21:28:04 24 4
gpt4 key购买 nike

我有一个递归函数,它将重复该函数,直到不满足 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)

最佳答案

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 移动即可解决问题。

关于scala - 递归函数不返回 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12658588/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com