1. static void h2(int n){
2. if(n<2)
3. h2(n 1);
4. System.out.print(n " ");
5. if(n<2)
6. h2(n 1);
7. }
如果我給出這個函式的結果,這個函式是一個遞回函式:有人h2()可以
向我解釋這個函式是如何作業的嗎?
我還想知道下一個 ==> 例如在呼叫函式時代碼是否繼續到下一行并列印值,或者它繼續并重新開始函式?n=02 1 2 0 2 1 2 3h2(n 1);n
我添加了一些列印,所以我可以看到發生了什么:
1. static void h2(int n){
2. int i=0;
3. if(n<2){
4. System.out.println("i=" ( i) " first n=" n " ");
5. h2(n 1);
6. }
7. System.out.println("i=" ( i) " n=" n);
8. if(n<2){
9. System.out.println("\ni=" ( i) " second n=" n " ");
10. h2(n 1);
11. }
12. }
這是這段代碼的輸出:
i=1 first n=0
i=1 first n=1
i=1 n=2
i=2 n=1
i=3 second n=1
i=1 n=2
i=2 n=0
i=3 second n=0
i=1 first n=1
i=1 n=2
i=2 n=1
i=3 second n=1
i=1 n=2
uj5u.com熱心網友回復:
這是一個測驗應用程式,向您顯示程式執行的跟蹤(由于使用 需要 Java 11 String#repeat(int)):
public class Main {
private static int depth;
public static void main(String[] args) {
foo(0);
}
public static void foo(int n) {
printDebug("Invoked foo(" n ")");
if (n < 2) {
printDebug("Recursively call foo(" n " 1)");
depth ;
foo(n 1);
depth--;
printDebug("Returned from recursive call of foo(" n " 1)");
} else {
printDebug("Skip recursive call");
}
// this is the 'System.out.print(n " "); line'
printDebug("PRINT VALUE OF n AND A SPACE (n=" n ")");
if (n < 2) {
printDebug("Recursively call foo(" n " 1)");
depth ;
foo(n 1);
depth--;
printDebug("Returned from recursive call of foo(" n " 1)");
} else {
printDebug("Skip recursive call");
}
}
private static void printDebug(String msg) {
System.out.println(" ".repeat(depth) msg);
}
}
遞回函式已重命名foo并稍作修改以適應除錯陳述句。當您運行上述內容時,輸出將是:
Invoked foo(0)
Recursively call foo(0 1)
Invoked foo(1)
Recursively call foo(1 1)
Invoked foo(2)
Skip recursive call
PRINT VALUE OF n AND A SPACE (n=2)
Skip recursive call
Returned from recursive call of foo(1 1)
PRINT VALUE OF n AND A SPACE (n=1)
Recursively call foo(1 1)
Invoked foo(2)
Skip recursive call
PRINT VALUE OF n AND A SPACE (n=2)
Skip recursive call
Returned from recursive call of foo(1 1)
Returned from recursive call of foo(0 1)
PRINT VALUE OF n AND A SPACE (n=0)
Recursively call foo(0 1)
Invoked foo(1)
Recursively call foo(1 1)
Invoked foo(2)
Skip recursive call
PRINT VALUE OF n AND A SPACE (n=2)
Skip recursive call
Returned from recursive call of foo(1 1)
PRINT VALUE OF n AND A SPACE (n=1)
Recursively call foo(1 1)
Invoked foo(2)
Skip recursive call
PRINT VALUE OF n AND A SPACE (n=2)
Skip recursive call
Returned from recursive call of foo(1 1)
Returned from recursive call of foo(0 1)
每行的縮進顯示遞回呼叫的當前深度(更多縮進意味著更深的遞回)。如果您查看PRINT VALUE OF n AND A SPACE (n=#)行的順序,您會看到原始遞回函式的輸出將是:
2 1 2 0 2 1 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/478706.html
