c++ - 斐波那契数的递归函数
问题描述
我必须编写一个简单的程序,如下所示:“给定一个非负整数 n,使用递归找到第 n 个斐波那契数”。我认为这意味着,对于用户输入的任何值,我都必须得到斐波那契数。例如,如果用户输入 4,我将不得不获取斐波那契数列中的第 4 个值(即 2)。下面是我写的内容,但是我的递归有问题,因为它在我运行它时会崩溃。感谢任何帮助...
int userValue;
int fibo;
int fib(int n);
int fibValue;
int main() {
cout << "Please provide your value" << endl;
cin >> userValue;
while (userValue < 0) {
cout << "Fibonacci numbers only start at 0, please try again: " << endl;
cin >> userValue;
}
if (userValue == 1 || userValue == 0) {
cout << "Fibonacci result is: " << userValue << endl;
return 0;
}
else {
fib(userValue);
cout << "Fibonacci result is: " << fibValue << endl;
//return 0;
}
}
int fib(int n)
{
fibValue = fib(n - 1) + fib(n - 2);
return fibValue;
}
解决方案
问题出在fib
方法上。没有提供终止条件。因此,递归将在循环中发生而不会终止。
首先,尝试通过提供多个输入来调试任何问题,您将了解问题所在。
在你的情况下,
对于假设n=3
,
跟踪将是这样的
fib(3) -> which further invokes fib(2) and fib(1)
fib(2) -> which further invokes fib(1) and fib(0)
现在因为没有终止条件
fib(0) will further invoke fib(-1) and fib(-2)
由于负值 fib 不存在终止条件,因此应提供递归停止并返回结果。
对于斐波那契数,终止条件如下:
if(n == 0){
return 0;
}else if (n == 1){
return 1;
}
很少参考
https://blog.hartleybrody.com/debugging-code-beginner/
https://www.codementor.io/mattgoldspink/how-to-debug-code-efficiently-and-effectively-du107u9jh%60
希望这可以帮助。谢谢。
推荐阅读
- java - 在其他语言中状态为 200 时,在 Java 中登录后重定向 302
- php - 可以在类中获取数据但返回时只发送布尔值php PDO?
- c# - HtmlAgilityPack NullReferenceException 错误
- python - PySpark:连接数据类型为“Struc”的两列-> 错误:由于数据类型不匹配而无法解决
- java - 使按钮适应 JavaFX 中的窗口大小调整(重新定位)
- blob - 在复制活动期间或在 blob 数据集中指定名称时将日期时间动态附加到文件名
- php - 为什么我在我的本地主机上得到未定义的变量或索引,而不是我的实时服务器?
- sql - 比较 Oracle 中的 2 个列表
- python - 如何修复标签数量与样本数量不匹配?
- php - 将点击事件附加到表格单元格的最佳方式是什么?