Recursive Fibonacci

前端 未结 13 1663
情歌与酒
情歌与酒 2020-12-07 18:52

I\'m having a hard time understanding why

#include 

using namespace std;

int fib(int x) {
    if (x == 1) {
        return 1;
    } else {
         


        
13条回答
  •  南方客
    南方客 (楼主)
    2020-12-07 19:25

    By definition, the first two numbers in the Fibonacci sequence are 1 and 1, or 0 and 1. Therefore, you should handle it.

    #include 
    using namespace std;
    
    int Fibonacci(int);
    
    int main(void) {
        int number;
    
        cout << "Please enter a positive integer: ";
        cin >> number;
        if (number < 0)
            cout << "That is not a positive integer.\n";
        else
            cout << number << " Fibonacci is: " << Fibonacci(number) << endl;
    }
    
    int Fibonacci(int x) 
    {
        if (x < 2){
         return x;
        }     
        return (Fibonacci (x - 1) + Fibonacci (x - 2));
    }
    

提交回复
热议问题