【问题标题】:Nth Fibonacci number第 N 个斐波那契数
【发布时间】:2022-12-10 21:15:16
【问题描述】:

我无法仅打印第 n 个斐波那契数。 在我的代码中,当用户说要打印第 n 个 trem 时,它会打印第 n 个术语的系列,但我只想获得第 n 个术语的输出 例如 如果我说 num=4 输出应为 2

请指导

这是代码:

N= int(input("How many terms? "))


N1 = 0
N2 = 1
sum = 2


if N <= 0:
   print("Plese enter a positive integer")
elif N == 1:
   print("Fibonacci sequence:")
   print(N1)
else:
   print("Fibonacci sequence:")
   print(N1,",",N2,end=' , ')
   while sum < N:
       Nth = N1 + N2
       print(Nth,end=' , ')

       N1 = N2
       N2 = Nth
       sum += 1

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    打印 stmt 应该在循环之外

    N= int(input("How many terms? "))
    
    
    N1 = 0
    N2 = 1
    sum = 2
    
    
    if N <= 0:
       print("Plese enter a positive integer")
    elif N == 1:
       print("Fibonacci sequence:")
       print(N1)
    else:
       print("Fibonacci sequence:")
       print(N1,",",N2,end=' , ')
       while sum < N:
           Nth = N1 + N2
    
           N1 = N2
           N2 = Nth
           sum += 1
       print(Nth,end=' , ')
    

    【讨论】:

      【解决方案2】:

      更简单的代码,来自 "How to Think Like a Comptuer Scientist: Python" 书,

      def fibonacci (n):
          if n == 0:
              return 0
          elif n == 1:
              return 1
          else:
              return fibonacci(n-1) + fibonacci(n-2)
      

      只需调用 fibonacci 将您的第 n 个术语作为参数。

      【讨论】:

        【解决方案3】:

        要获得该输出,您只需将 n 的值减 1,然后进行所有计算。 例如:

        def fib(n):
            n = n-1
            a, b = 0, 1
            count = 1
            while count <= abs(n):
                next = a + b
                a = b
                b = next
                count += 1
            return a 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-10-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-04-17
          • 1970-01-01
          • 1970-01-01
          • 2021-07-18
          相关资源
          最近更新 更多