【问题标题】:Fibonacci number using Repeat loop使用重复循环的斐波那契数
【发布时间】:2020-12-03 16:12:45
【问题描述】:

我如何使用repeat 循环来找到最大的斐波那契数,直到例如1000(所以小于1000)?

我发现可以使用while 循环执行此操作,但我将如何使用repeat 执行此操作?

【问题讨论】:

  • 为什么要专门使用repeat

标签: r fibonacci


【解决方案1】:

你需要测试从repeat变成break的条件,否则它将永远循环下去:

# Set the first two numbers of the series
x <- c(0, 1)

repeat {
  # Add the last two numbers of x together and append this value to x
  x <- c(x, sum(tail(x, 2))) 

  # Check whether the last value of x is above 1000, if so chop it off and break
  if(tail(x, 1) > 1000) {
    x <- head(x, -1)
    break
  }
}

# x now contains all the Fibonacci numbers less than 1,000
x
#> [1]   0   1   1   2   3   5   8  13  21  34  55  89 144 233 377 610 987

【讨论】:

  • 非常感谢!这正是我正在寻找的 - 但由于某种原因它不起作用并返回错误“错误:“}”中的意外'}'“我似乎无法修复它?
  • @EwaMichalska 抱歉 - 有错字。它现在应该可以工作了
猜你喜欢
  • 1970-01-01
  • 2016-04-28
  • 2020-01-26
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
  • 2015-04-30
  • 2023-03-12
  • 2023-03-23
相关资源
最近更新 更多