有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java 1.6中未给出阶乘递归异常

为什么我在下面的代码中没有得到任何异常? 运行完这段代码后,我在测试中得到了一个无限循环。事实(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));
    }
}

比如说我正在使用

return(a+b); 

它成功地执行了递归的问题是什么 显示错误


共 (2) 个答案

  1. # 1 楼答案

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

    返回

    fact(20)
    

    它回来了

    fact (380)
    

    它回来了

    fact (379*380)
    

    哪个

    它不会返回任何内容,并且会导致堆栈溢出(调用堆栈上使用了太多内存)

               return fact(m-1) * m;
    

    应该有用

    我强烈建议您再次阅读基础知识和示例(这里,例如-http://www.toves.org/books/java/ch18-recurex/index.html

    试着自己写递归树,以了解发生了什么

  2. # 2 楼答案

    使用循环(无递归)计算阶乘的另一种方法:

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