gpt4 book ai didi

c++ - C++ 中的斐波那契数列 : Control reaches end of non-void function

转载 作者:行者123 更新时间:2023-11-27 23:25:52 24 4
gpt4 key购买 nike

在练习递归函数时,我为斐波那契数列编写了这段代码,并且(阶乘)程序没有运行并显示错误“控制到达非空函数的结尾”我怀疑这是关于最后一次迭代达到零并且不知道如何处理负整数。我试过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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com