【发布时间】:2014-01-05 06:01:03
【问题描述】:
我正在自学 C++,来自 Sams Teach Yourself C++ In One Hour A Day,在第 150 页,作者使用斐波那契数列讨论了递归函数。
他使用以下代码:
#include <iostream>
using namespace std;
int GetFibNumber(int FibIndex)
{
if(FibIndex < 2 )
return FibIndex;
else
return GetFibNumber(FibIndex - 1) + GetFibNumber(FibIndex - 2);
}
int main()
{
cout << " Enter 0 based index of desired Fibonacci Number: ";
int Index = 0;
cin >> Index;
cout << " Fibonacci number is: " << GetFibNumber(Index) << endl;
return 0;
}
有什么区别
return GetFibNumber(FibIndex - 1) + GetFibNumber(FibIndex - 2);
和
返回 FibIndex - 1 + FibIndex - 2;
为什么一定要在内部调用函数?
提前感谢您!
【问题讨论】:
-
能否请您提供一个您所做的示例并更清楚地解释您的问题。
-
第 9 行现在读到了什么?如果没有这两个函数调用,它将无法计算斐波那契数列。
-
请看一下斐波那契数列是什么en.wikipedia.org/wiki/Fibonacci_number 没有最后一个
GetFibNumber(FibIndex - 1) + GetFibNumber(FibIndex - 2)计算是错误的。 -
@bkausbk 是的,我知道这一点。我只是删除了您刚刚复制和粘贴的行中的“GetFibNumber”。
-
@JOG-Design:只要输入参数 FibIndex 很小(