Recursive Fibonacci

前端 未结 13 1695
情歌与酒
情歌与酒 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:29

    The reason is because Fibonacci sequence starts with two known entities, 0 and 1. Your code only checks for one of them (being one).

    Change your code to

    int fib(int x) {
        if (x == 0)
            return 0;
    
        if (x == 1)
            return 1;
    
        return fib(x-1)+fib(x-2);
    }
    

    To include both 0 and 1.

提交回复
热议问题