寻找Fibonacci序列的术语

时间:2016-04-10 11:38:27

标签: ruby

我试图找到不超过100的斐波那契序列的所有项。这是我的代码:

fibonacci_sequence = [1,2]
index = fibonacci_sequence.length

# finding next term, term 3
# current index is 2
next_term = fibonacci_sequence[index - 2] + fibonacci_sequence[index - 1]
fibonacci_sequence.push(next_term)
index += 1

until next_term > 100 do
  next_term = fibonacci_sequence[index - 2] + fibonacci_sequence[index - 1]
  fibonacci_sequence.push(next_term)
  index += 1
end

p fibonacci_sequence

当我尝试运行代码时,还会包含值144。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

你的情况:

until next_term > 100

在更新前评估next_term。在循环中,您计算​​下一个next_term并添加它。所以你的循环在条件满足后结束一次迭代。

您也不需要index,也不需要单独进行第一次迭代。

将其更改为:

fibonacci_sequence = [1, 2]
loop do
  next_term = fibonacci_sequence[-2] + fibonacci_sequence[-1]
  break if next_term > 100
  fibonacci_sequence.push(next_term)
end
p fibonacci_sequence # => [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]