簡體   English   中英

Java 1.6中未提供階乘遞歸異常

[英]Factorial recursion Exception not given in java 1.6

為什么在以下代碼中沒有任何異常? 運行此代碼后,在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));
    }
}

雖然說例如我正在使用

return(a+b); 

它成功執行了遞歸的問題,顯示了一個錯誤???

您在事實方法的返回值表達式中有一個錯誤。 它應該是

      return fact(m-1) * m;
      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

嘗試編寫遞歸樹,以了解發生了什么。

另一種使用周期計算階乘的方法(無遞歸):

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