首页 > 解决方案 > 如何获得 0 作为我的斐波那契序列的第一项?

问题描述

当输入为 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

标签: pythonwhile-loopfibonacci

解决方案


您当前的代码可以通过返回present而不是nextterm.

如果你很好奇,Python 中常见的 Fibonacci 实现通常如下所示。这个版本中的变量命名对我来说似乎更直观一些。

def fib(n):
    cur, nxt = (0, 1)
    while n > 0:
        cur, nxt = (nxt, cur + nxt)
        n -= 1
    return cur

推荐阅读