This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 10 years ago.
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(4)
我猜当你调用
fib(-2)
时,它会调用fib(2)
fib(2)
调用fib(1)
和fib(0)
fib(1)
调用fib(0)
和fib(-1)
code>fib(-1)
调用fib(1)
这是永无休止的循环I guess that when u call
fib(-2)
it callsfib(2)
fib(2)
callsfib(1)
andfib(0)
fib(1)
callsfib(0)
andfib(-1)
fib(-1)
callsfib(1)
and this is never-ending loop这将导致无限递归。您需要两种终止情况,而不是一种。
以
fib(1)
为例。这将调用fib(0)
和fib(-1)
。fib(0)
将终止,但fib(-1)
将调用fib(1),然后再次调用
fib(-1 )` 无穷无尽。解决方案:如果
n==0
或n==1
则终止递归。旁注:
fib(0)
通常定义为 0,而不是 1。This will cause infinite recursion. You need two terminating cases, not one.
Take for example
fib(1)
. This will callfib(0)
andfib(-1)
.fib(0)
will terminate, butfib(-1)
will callfib(1), which will then again call
fib(-1)` ad infinitum.Solution: Terminate the recursion if
n==0
orn==1
.Sidenote:
fib(0)
is usually defined as 0, not 1.哎呀,我犯了一个愚蠢的错误,忘记了 n== -1 基本情况。应该是:
现在一切都按预期进行。
Oops I made a stupid mistake forgetting the n== -1 base case. It should be:
Now everything works as expected.