Fawcett Fawcett
Fawcett Fawcett

Reputation: 47

Fibonacci numbers program

Im trying to write a program that displays the FIBONACCI NUMBERS, however, the numbers don't print out correctly and are always one number too high for what the Fibonacci number is meant to be, can anyone understand why?

This is the code i have:

a, b = 0, 1
while b < 1000:
      print(b, '', end='')
      a, b = b, a + b

(have to use those 4 lines of code)

And this is the output I get

1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

and this is the output im looking for 0 1 2 4 7 12 20 33 54

the program should also start at 0 not 1

Upvotes: 0

Views: 93

Answers (2)

Nikhil G
Nikhil G

Reputation: 559

Printing 'a' instead of 'b' will solve your problem. Try this code this would solve your problem.

a, b = 0, 1
while b < 1000:
    print(a, '', end='')
    a, b = b, a + b

while i traced your code i got,

  • 1st iter : a=0,b=1 2nd iter : a=1,b=1 3rd iter : a=1,b=2 4th iter : a=2,b=3 5th iter : a=3,b=5 and continues..

Upvotes: 1

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

Try printing a instead of b. a and b are the first two terms of the sequence, so if you want to print the first term you have to print a.

To get your desired output, instead of the usual fibbonacci sequence, you'll also need to increase b by one, every iteration:

a, b = b, (a + b + 1)

Upvotes: 3

Related Questions