如何让 0 作为我的斐波那契数列的第一项?
How to get 0 as the first term of my fibonacci sequece?
当输入为 0 时,我无法弄清楚如何将 0 显示为斐波那契数列函数的输出。如何使用 while 循环来实现?
def Fibonacci(n):
i= 0
present = 1
previous = 0
while i <= n:
nextterm = present + previous
present = previous
previous = nextterm
i += 1
return nextterm
I expect the output of Fibonacci(0) to be 0
您当前的代码可以通过返回 present
而不是 nextterm
来修复。
如果您好奇,Python 中常见的斐波那契实现通常如下所示。这个版本的变量命名对我来说似乎更直观一些。
def fib(n):
cur, nxt = (0, 1)
while n > 0:
cur, nxt = (nxt, cur + nxt)
n -= 1
return cur
一定是返回1,当n=0时进入循环,下期置1。
当输入为 0 时,我无法弄清楚如何将 0 显示为斐波那契数列函数的输出。如何使用 while 循环来实现?
def Fibonacci(n):
i= 0
present = 1
previous = 0
while i <= n:
nextterm = present + previous
present = previous
previous = nextterm
i += 1
return nextterm
I expect the output of Fibonacci(0) to be 0
您当前的代码可以通过返回 present
而不是 nextterm
来修复。
如果您好奇,Python 中常见的斐波那契实现通常如下所示。这个版本的变量命名对我来说似乎更直观一些。
def fib(n):
cur, nxt = (0, 1)
while n > 0:
cur, nxt = (nxt, cur + nxt)
n -= 1
return cur
一定是返回1,当n=0时进入循环,下期置1。