python中fibonacci排序的困难

2024-06-26 13:59:14 发布

您现在位置:Python中文网/ 问答频道 /正文

(我在上计算机基础课,这是家庭作业)

我试图创建一个以“n”为参数的基本斐波那契序列。你知道吗

到目前为止,当我在空闲状态下运行程序时,我所拥有的似乎工作正常

def fibonacci(n):
    a=0
    b=1
    n = input("How high do you want to go? If you want to go forever, put 4ever.")
    print(1)
    while stopNumber=="4ever" or int(stopNumber) > a+b:
       a, b = b, a+b
       print(b)
fibonacci(n)

但当我试图运行程序,使它显示的信息,我得到这个错误

  Traceback (most recent call last):
 File "C:/Users/Joseph/Desktop/hope.py", line 10, in <module> fibonacci(n)
 NameError: name 'n' is not defined

你知道我该怎么解决这个问题吗?你知道吗


Tags: to程序yougo参数状态计算机序列
2条回答

由于fibonacci函数正在接受输入,因此不需要传递参数。但是在错误的情况下,没有在全局范围中定义n。我只想去掉n参数。另外,只要用n替换stopNumber。你知道吗

def fibonacci():
    a=0
    b=1
    n = input("How high do you want to go? If you want to go forever, put 4ever.")
    print(1)
    while n == "4ever" or int(n) > a+b:
       a, b = b, a+b
       print(b)

fibonacci()

调用fibonacci时,不应传递尚未从用户读取的n。而且,您正在使用stopNumber(而不是n)。我想你想

def fibonacci():
    a=0
    b=1
    stopNumber = input("How high do you want to go? " +
        "If you want to go forever, put 4ever.")
    print(1)
    while stopNumber=="4ever" or int(stopNumber) > a+b:
       a, b = b, a+b
       print(b)

fibonacci()

相关问题 更多 >