Write a program to calculate the Fibonacci number, not exceeding the predetermined number N

Fibonacci numbers are calculated using the following relations: F0 = 0; F1 = 1; Fi = Fi-1 + Fi-2 для i > 1 F0 = 0; F1 = 1; Fi = Fi-1 + Fi-2 для i > 1

 Sub Main() Dim f1&, f2&, N& f1 = f2 = 1 N = 20 While f1 <= N f1 = f1 + f2 f2 = f1 - f2 End While MsgBox f2 End Sub 

For some reason, when executing this code, Excel hangs tight. I would be very grateful if you tell me what the error is so that I will not commit it in the future.

PS I can write this program in any other language, but VBA doesn’t give me anything.

    1 answer 1

    And how did it work for you? In VBA While statement syntax

     While condition [statements] Wend 

    But if it hangs, it means that it somehow managed to run)

    Pay attention to the line:

     f1 = f2 = 1 

    f1 , f2 - variables of type Long , equal to zero by default. The condition is passed to the f1 variable.

     f2 = 1 ---> 0 = 1 ---> False 

    f1 converts the logical value to itself

      f1 = 0 

    Because of this, the subsequent cycle becomes infinite - f1 and f2 do not go from zero.

    Correct entry

     f1 = 1: f2 = 1 

    Well, an extra touch

     Const N& = 20 
    • Thank you very much! You really helped! - Vladislav Novikov