递归方法的问题 ( "missing return statement" )



所以我有一个程序正在运行一堆不同的递归方法,我无法编译/运行它。根据我的电脑,错误在于这种方法:

public static int fibo(int n)
    // returns the nth Fibonacci number
    {
     if (n==0)
     {
      return 0;
     }
     else if (n==1)
     {
       return 1;
     }
     else if (n>1)
     {
      return fibo(n-1) + fibo(n-2);
     }

    }

我在主方法中正确调用了这个方法,所以问题出在这段代码中。

我想我可以在这方面帮你。在else if之后添加return n;。在代码之外,但在最后一个curlicue之前。

只要n ≥ 0 btw,代码就会工作;这里的另一张海报是正确的,你可能想添加一些东西来捕捉这个错误。

确保所有可能的路径都有一个return语句。在您的代码中,如果n<0,没有返回语句,编译器识别出这一点,并抛出错误。

public static int fibo(int n)
    // returns the nth Fibonacci number
    {
     if (n<=0)
     {
      return 0;
     }
     else if (n==1)
     {
       return 1;
     }
     else // All other cases, i.e. n >= 1
     {
      return fibo(n-1) + fibo(n-2);
     }
    }

相关内容

最新更新