gpt4 book ai didi

java - 错误 "Missing return statement"

转载 作者:行者123 更新时间:2023-12-01 22:04:52 27 4
gpt4 key购买 nike

我正在运行此 java 代码,但收到错误“缺少返回语句”请帮忙。我在 Windows 中使用 cmd 运行。

public class Fibonocci {

public static void main(String[] args) {

int i, limit, c;
i = 0;
limit = 5;
System.out.println("Fibonocci series :");
for (c = 1; c <= limit; c++) {
System.out.println(fib(i));
System.out.println("/n");
i++;
}

}

public static int fib(int p) {
if (p == 0) {
return 0;
}
if (p == 1) {
return 1;
} else if (p > 1) {
return (fib(p - 1) + fib(p - 2));
}
}
}

最佳答案

如果 p<0,您的代码不会返回任何内容.

您可以将其更改为:

  public static int fib(int p){
if (p<=0) // or perhaps you wish to throw an exception if a negative value is entered
return 0;
else if (p==1)
return 1;
else // when you end the if statement in else instead of else-if
// your method is guaranteed to return something for all inputs
return(fib(p-1)+fib(p-2));
}

关于java - 错误 "Missing return statement",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32987598/

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