【问题标题】:Can't Get Correct Fibonacci Sequence From Scala Code无法从 Scala 代码中获得正确的斐波那契数列
【发布时间】:2017-11-18 09:01:19
【问题描述】:

我编写了以下代码来打印斐波那契数列中的前 10 个数字。我期望输出为 0,1,1,2,3,5,8,13,21,34。相反,我得到 0,1,2,3,5,8,13,21,34,55。这是代码 -

var a = 0
var b = 0
var i = 0

while(i < 10) {
  val c = a +b
 a = b
 b = c
 i = i + 1
 if (a < 1) a = 1

println(b)
 }

【问题讨论】:

标签: scala


【解决方案1】:

这应该可行:

var a = 0 
var b = 1 
var i = 0 

while(i < 10) {
  println(a)
  val c = a + b 
  a = b 
  b = c 
  i = i + 1 
}

但这不是功能性的,所以不是真正的scala

【讨论】:

  • 刚刚学习 Scala 并使用“工作表”来测试设置值等的不同方式。
【解决方案2】:

这是一个展示一些基本 Scala 功能的递归解决方案:

// Function definitions can have types with default values
def fib(a: Int = 0, b: Int = 1, count: Int = 2): List[Int] = {

  // Calculate the next value
  // In functional programming we prefer immutability so always try to use val instead of var
  val c = a + b

  // Stopping criteria, send back a list containing the latest value
  if (count >= 10) {
    List(c)
  }

  // If this is the first iteration create the first few fibonacci numbers, and make a recursive call
  // Adding one list to another is done using the ++ function
  else if (a == 0 && b == 1) {
    List(a, b, c) ++ fib(b, c, count + 1)
  }

  // If this wasn't the first iteration, just add the latest element and make the recursive call
  else {
    c +: fib(b, c, count + 1)
  }
}

// Since we gave default values the function parameters, you don't need to pass any when you call the function here
println(fib())

【讨论】:

  • 感谢 Tyler 清晰准确的解释!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-31
  • 2020-01-18
  • 1970-01-01
  • 1970-01-01
  • 2014-05-19
  • 1970-01-01
  • 2015-06-05
相关资源
最近更新 更多