0

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

0

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

5 Comments

so like print(a, ' ' , end= ' ' )?
That gives the output of 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 , where as i thought the fibonacci was 0 1 2 4 7 12 20 33 54
@FawcettFawcett Looks like your output is correct but definition is wrong, en.wikipedia.org/wiki/Fibonacci_number
My applogies, my lecturer has given us a assignment that gives the first few numbers of the sequence and says the out put should look like that
Looks like you just need to add 1 to b every iteration to get the sequence you're looking for.
1

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..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.