我编写了以下代码来打印Fibonacci序列中的前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)
}
答案 0 :(得分:0)
这应该有效:
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
答案 1 :(得分:0)
这是一个递归解决方案,展示了一些基本的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())