【发布时间】:2020-12-03 16:12:45
【问题描述】:
我如何使用repeat 循环来找到最大的斐波那契数,直到例如1000(所以小于1000)?
我发现可以使用while 循环执行此操作,但我将如何使用repeat 执行此操作?
【问题讨论】:
-
为什么要专门使用
repeat?
我如何使用repeat 循环来找到最大的斐波那契数,直到例如1000(所以小于1000)?
我发现可以使用while 循环执行此操作,但我将如何使用repeat 执行此操作?
【问题讨论】:
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
【讨论】: