怎么用python計(jì)算斐波那契數(shù)列第n項(xiàng)

小億
241
2024-05-29 18:49:13

下面是一個(gè)使用Python計(jì)算斐波那契數(shù)列第n項(xiàng)的示例代碼:

def fibonacci(n):
    if n <= 0:
        return "輸入錯(cuò)誤,請(qǐng)輸入大于0的整數(shù)"
    elif n == 1:
        return 0
    elif n == 2:
        return 1
    else:
        a, b = 0, 1
        for _ in range(2, n):
            a, b = b, a + b
        return b

n = int(input("請(qǐng)輸入要計(jì)算的斐波那契數(shù)列的第幾項(xiàng):"))
result = fibonacci(n)
print(f"第{n}項(xiàng)的斐波那契數(shù)是:{result}")

你可以將上面的代碼保存到一個(gè).py文件中,然后在命令行中運(yùn)行該文件,輸入要計(jì)算的斐波那契數(shù)列的第幾項(xiàng),程序?qū)⑤敵鰧?duì)應(yīng)的結(jié)果。

0