使用重复循环的斐波那契数

Fibonacci number using Repeat loop

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

我发现可以使用 while 循环来完成它,但是我如何使用 repeat 来完成它?

你需要测试让你从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