作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在练习递归函数时,我为斐波那契数列编写了这段代码,并且(阶乘)程序没有运行并显示错误“控制到达非空函数的结尾”我怀疑这是关于最后一次迭代达到零并且不知道如何处理负整数。我试过return 0,return 1,但都不好。有什么建议吗?
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <ctime>
using namespace std;
int fib(int n) {
int x;
if(n<=1) {
cout << "zero reached \n";
x= 1;
} else {
x= fib(n-1)+fib(n-2);
return x;
}
}
int factorial(int n){
int x;
if (n==0){
x=1;
}
else {
x=(n*factorial(n-1));
return x;
}
}
最佳答案
改变
else if (n==1)
x=1;
到
else if (n==1)
return 1;
然后 fib()
应该适用于所有非负数。如果你想简化它并让它适用于所有数字,请使用类似的东西:
int fib(int n) {
if(n<=1) {
cout << "zero reached \n";
return 1;
} else {
return fib(n-1)+fib(n-2);
}
}
关于c++ - C++ 中的斐波那契数列 : Control reaches end of non-void function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9569825/
我是一名优秀的程序员,十分优秀!