第N个斐波纳契数

时间:2014-11-28 18:41:05

标签: python-3.x

我无法仅打印第n个斐波纳契数。 在我的代码中,当用户说要打印第n个trem时它打印系列到第n个术语但是我想得到输出只有第n个术语 例如 如果我说num = 4 out put应为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

3 个答案:

答案 0 :(得分:1)

print 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=' , ')

答案 1 :(得分:0)

更简单的代码,来自"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)

请将斐波那契称为第n个词作为参数。

答案 2 :(得分:0)

要获得该输出,您可以简单地将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