簡體   English   中英

需要幫助解密Java中的析因代碼

[英]Need help deciphering a factorial code in Java

我已經看到了使用for循環的答案,我理解,但是我最近遇到了這個代碼,我不知道它是如何工作的。

public class learn {

    public static int factorial (int N){
        if (N<=1 ) return 1; // won't this mean that "1" is returned at the end all the time?
        else return (N*factorial (N-1)); /* since there's no variable storing the sum
                                            I don't get how this is working out either, 
                                            won't it just be returned and lost?*/
    }
    public static void main(String[] args) {
        System.out.println(factorial(4));
    }
}

來自python背景,所以也許我誤解了java中的返回... [編輯]似乎return 1也是用Python編寫的,所以它可能不是語言問題,我只是不知道遞歸函數如何結束 (我了解過程如何進行 - 它是一個自稱的函數)。

以下是我如何解釋此代碼(錯誤地)的說明:

  1. factorial(4)被稱為
  2. 4超過1,所以else語句將運行 - 4*factorial(3)
  3. factorial(3)被調用 - else語句再次運行 - 3*factorial(2)
  4. factorial(2)被稱為 - 2*factorial(1) 此時,我們有4 * 3 * 2 * 1,但代碼僅在if (N<=1) return 1行停止的事實意味着if (N<=1) return 1而不是總和權利? (我顯然錯了,因為控制台打印了正確的數字24

這不意味着“1”總是在最后返回嗎?

不,當N小於1時,它將僅返回1.(根據您的條件, if (N<=1 ) return 1; )對於所有其他情況,它將遞歸遞歸。

因為沒有變量存儲總和我不知道這是如何工作的,它不會只是返回和丟失?

當一個方法返回時,它退出當前方法並返回到調用點從那里繼續 為簡單起見,請采用以下方案:methodA調用methodB,methodB調用methodC:

public void methodA(){
    print("entering method A..");   //(1)methodA invoked..
    methodB();                      //(2)call methodB
    print("exiting method A");      //(8)exit from methodB, continue from here
}

public void methodB(){               
    print("entering method B..");   //(3)mthodB invoked..
    methodC();                      //(4)call methodC
    print("exiting method B");      //(7)exit from methodC, continue from here. exit methodB
}

public void methodC(){
    print("entering method C..");   //(5)methodC invoked..
    print("exiting method C");      //(6)exit methodC, continue from whoever called methodC
}

您將獲得如下結果:

entering method A..
entering method B..
entering method C..
exiting method C
exiting method B
exiting method A

如果你能理解方法A和C的程序流程。現在嘗試理解一個叫做“本身”的方法。

//Let say N is 3.. 
public static void main(String[] args){
    factorial(3);                    //(9)
}

public static int factorial (int N)  //(1)N:3, (3)N:2, (5)N:1
{
    if (N<=1 ) 
        return 1;                    //(6)Ret 1, return and continue from whoever called me
    else 
        return (N*factorial (N-1));  //(2), (4), (7)Ret 2*1, (8)Ret 3*2*1
}
  • 在(6),它通過返回1退出方法並從調用該方法的地方繼續。 它所在的地方是(7)。

  • 在(7),它通過返回N * 1(2 * 1 = 2)退出該方法並從調用該方法的地方繼續。 它被調用的地方是(8)。

  • 在(8),它通過返回N * 2(3 * 2 = 6)退出該方法並從調用該方法的地方繼續。 它被稱為的地方是(9)這是主要的方法。

如果參數N等於或小於1,則if語句僅返回1,否則將執行else子句。 在else子句中,由於它返回參數N的乘積和factorial(N-1)的返回值,因此Java需要等待factorial(N-1)返回一個值才能進行乘法並返回值。 不需要將參數N的值存儲到字段中,因為參數也是變量,只是它的值從方法的調用者傳遞。

在您的代碼中, factorial被調用4次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM