递归斐波纳契 [英] Recursive Fibonacci

查看:176
本文介绍了递归斐波纳契的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解为什么

  #include< iostream> 

using namespace std;

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

int main(){
cout< fib(5)<< endl;
}

会导致分段错误。 $ x == 2

当x <1时, / code>您呼叫 fib(1) fib(0)

  return fib(2-1)+ fib(2-2); 

考虑 fib(0)正在评估...


I'm having a hard time understanding why

#include <iostream>

using namespace std;

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

int main() {
    cout << fib(5) << endl;
}

results in a segmentation fault. Once x gets down to 1 shouldn't it eventually return?

解决方案

When x==2 you call fib(1) and fib(0):

return fib(2-1)+fib(2-2);

Consider what will happen when fib(0) is evaluated...

这篇关于递归斐波纳契的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆