为什么我的递归斐波那契实现是用 C++ 编写的?段错误?
我很难理解为什么
#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 降到 1,它最终不应该返回吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
当
x==2
调用fib(1)
和fib(0)
时:考虑当
fib(0) 时会发生什么
被评估...When
x==2
you callfib(1)
andfib(0)
:Consider what will happen when
fib(0)
is evaluated...原因是斐波那契数列以两个已知实体 0 和 1 开始。您的代码仅检查其中之一(是 1)。
将代码更改为
同时包含 0 和 1。
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
To include both 0 and 1.
为什么不使用迭代算法呢?
Why not use iterative algorithm?
根据定义,斐波那契数列中的前两个数字是 1 和 1,或者 0 和 1。因此,您应该处理它。
By definition, the first two numbers in the Fibonacci sequence are 1 and 1, or 0 and 1. Therefore, you should handle it.
我认为这个解决方案很短,看起来不错:
编辑:正如jweyrich提到的,真正的递归函数应该是:(
因为fib(0)= 0。但基于上面的递归公式,fib(0)将是1)
要理解递归算法,你应该在你的论文上画画,最重要的是:“经常思考正常”。
I think this solution is short and seem looks nice:
Edit : as jweyrich mentioned, true recursive function should be:
(because fib(0) = 0. but base on above recursive formula, fib(0) will be 1)
To understand recursion algorithm, you should draw to your paper, and the most important thing is : "Think normal as often".
在斐波那契数列中,前 2 个数字总是紧随 1,然后每次该值变为 1 或 2 时,它必须返回 1
in fibonacci sequence first 2 numbers always sequels to 1 then every time the value became 1 or 2 it must return 1
这是我用递归解决斐波那契问题的方法。
This is my solution to fibonacci problem with recursion.