问题
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
- The series starts with 0, you initialized it with 1.
- The update statement
n3=n1+n2
is outside the loop, how will it update? What is happening here isn3 = 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