【问题标题】:fibonacci sequencing difficulties in pythonpython中的斐波那契排序困难
【发布时间】:2015-06-12 05:48:12
【问题描述】:

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

我正在尝试创建一个以“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

知道如何解决这个问题吗?

【问题讨论】:

  • 如果你像这样创建函数,它不应该有任何参数,因为你从标准输入中获取它们。删除n 可以解决这个错误,但是会出现其他错误,而且你的算法也是错误的
  • @JosephMcMurray:算法没有错。
  • @MaciejBaranowski:他的算法没有错。

标签: python fibonacci


【解决方案1】:

由于您的 fibonacci 函数正在接受输入,因此并不完全需要传递参数。但是如果您的错误 n 未在全局范围内定义。我只想摆脱n 参数。另外,只需将stopNumber 替换为n

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()

【讨论】:

    【解决方案2】:

    当您调用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()
    

    【讨论】:

      猜你喜欢
      • 2014-05-23
      • 2014-05-25
      • 2013-08-03
      • 2013-02-24
      • 1970-01-01
      • 2014-06-03
      • 1970-01-01
      • 2019-06-04
      • 1970-01-01
      相关资源
      最近更新 更多