Fibonacci in Python - Simple solution [duplicate]

流过昼夜 提交于 2019-12-14 03:32:25

问题


n1 = 1
n2 = 1
n3 = n1 + n2
for i in range(10):
   n1 + n2
   print(n3)
   n1 = n2
   n2 = n3

According to what I know, this should be the simplest way of outputting the first 10 digits of the series, however, it prints 2 10 times. I don't understand why n1 doesn't get set to n2, and n2 doesn't get set to n3 after n3 has been printed.


回答1:


There are many issues with your code. And you should first learn and try as much as you can on your own. I am also a beginner so I know what you are thinking. For some quick edits to make it workable:

n1 = 0
n2 = 1
n3 = 0
for i in range(10):
   n3 = n1 + n3
   print(n3)
   n1 = n2
   n2 = n3
  1. The series starts with 0, you initialized it with 1.
  2. The update statement n3=n1+n2 is outside the loop, how will it update? What is happening here is n3 = 1 + 1 = 2 in your code stays the same and it doesn't change.



回答2:


n1 = -1
n2 = 1
n3 = n1 + n2
for i in range(10):
    n3 = n1 + n2
    print(n3)
    n1 = n2
    n2 = n3

This should work. You failed to store sum of n1 and n2. You are simply printing n3 ie 2 ten times. And try initiating n1 and n2 from -1.



来源:https://stackoverflow.com/questions/48251119/fibonacci-in-python-simple-solution

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!