令人困惑的斐波那契数程序
Confusing Fibonacci number program
本文关键字:程序 更新时间:2023-10-16
好的,所以我很难准确理解这个程序是如何工作的:
#include <iostream>
using namespace std;
int getFibNumber(int fibIndex)
{
if(fibIndex < 2)
return fibIndex;
else
return getFibNumber(fibIndex - 1) + getFibNumber(fibIndex - 2);
}
int main(int argc, char** argv)
{
cout << "Enter 0-based index of desired Fibonacci number: ";
int index = 0;
cin >> index;
cout << "Fibonacci number is: " << getFibNumber(index) << endl;
return 0;
}
具体来说,"getFibNumber(…)"在重复时会做什么(如果这是正确的单词)?如果传入的整数"fibIndex"大于或等于2,我不知道该怎么办。很抱歉问这么一个基本的问题,但我真的被这个问题难住了,我觉得我错过了什么。
正如这里提到的,这基本上是递归。
为了了解这个程序是如何工作的,我制作了一个递归树,初始fibIndex
为5
。
5 5 calls 4 and 3.
/
4 3 4 calls 3 and 2. 3 calls 2 and 1.
/ /
3 2 2 1 1 is base case, returns 1.
/ / /
2 1 1 0 1 0 2 is not base case. So calls 1 and 0.
/
1 0
这被称为递归。它不再使用循环来执行此操作,而是使用不同的参数再次调用该函数。最终,基本条件将为true,函数将返回,从而导致其他调用也返回。在正确的情况下,这可能是一个非常强大的工具。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- C++,系统无法执行指定的程序
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 重载操作程序时出错>>用于类中的字符串 memebr
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 试图在visual studio上用C++创建一个桌面应用程序
- 模板元程序查找相似的连续类型名称
- FFmpeg:制作一个应用程序比直接使用ffmepg更好吗
- 如何通过cpp程序运行shell脚本
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- IPC使用多个管道和分支进程来运行Python程序
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 基于boost的程序的静态链接——zlib问题
- 程序崩溃并显示"std::out_of_range"错误
- 在C应用程序中运行C++(带有STL)函数
- 使用mongocxx驱动程序时包含头文件问题
- 如何在c++程序中找到函数的地址