简体   繁体   English

Java 1.6中未提供阶乘递归异常

[英]Factorial recursion Exception not given in java 1.6

Why I am not getting any Exception in the following code? 为什么在以下代码中没有任何异常? After running this code I am getting an infinite loop mentioning at test.fact(t.java:32) No Compile-Time Error was found. 运行此代码后,在test.fact(t.java:32)上出现无限循环提及,未发现编译时错误。

class test
{

    int fact(int m) throws Exception
    {
        if (m==1)
        {
        return 1;
        }
    else
        return (fact ((m-1)*m));
    }
}

class main
{
    public static void main(String ar[]) throws Exception
    {
        test t = new test();
        System.out.println(t.fact(5));
    }
}

while say for example i am using 虽然说例如我正在使用

return(a+b); 

it executes successfully whats the problem with the recursion to show an error??? 它成功执行了递归的问题,显示了一个错误???

You have a mistake in the return value expression of fact method. 您在事实方法的返回值表达式中有一个错误。 It should be 它应该是

      return fact(m-1) * m;
      return (fact ((m-1)*m));

returns 退货

fact(20)

which returns 哪个返回

fact (380)

which returns 哪个返回

fact (379*380)

which .... 哪一个 ....

which never returns anything and should make a stack overflow (too much memory is used on the call stack). 它从不返回任何东西,并且应该导致堆栈溢出(调用堆栈上使用了太多内存)。

           return fact(m-1) * m;

should work. 应该管用。

I highly recommend you reading again the basics, and examples ( here, for example - http://www.toves.org/books/java/ch18-recurex/index.html ) 我强烈建议您再次阅读基础知识和示例(例如,在这里-http: //www.toves.org/books/java/ch18-recurex/index.html

Try writing the recursion tree yoursels, in order to understand what happens. 尝试编写递归树,以了解发生了什么。

Another way to calculate factorial using cycle (with no recursion): 另一种使用周期计算阶乘的方法(无递归):

int fact(int m) throws Exception
{
    int f = 1;
    for (int i = 0; i < m; f *= ++i);
    return f;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM