离开递归调用时如何打印
how to print when you have left a recursive call
如何在递归调用后打印到屏幕上。例如在执行下面的 ackermann 函数时。
acker(1,2);
public int acker(int m, int n){
System.out.println("Entered acker");
if(m == 0)
return n + 1;
if(n == 0)
return acker(m-1,1);
return acker(m-1, acker(m, n - 1));
}
当我进入acker方法时我可以打印,但是在该方法完成调用自身后我将如何打印。例如输出将是:
Entered acker
Entered acker
Entered acker
Entered acker
//Here it would say leaving because its not making another recursive call
重构以将 return 值分配给变量,打印您的消息,然后 return 值:
public int acker(int m, int n){
System.out.println("Entered acker");
int result;
if(m == 0)
result = n + 1;
else if(n == 0)
result = acker(m-1,1);
else
result = acker(m-1, acker(m, n - 1));
System.out.println( "Returning " + result + " from acker");
return result;
}
如何在递归调用后打印到屏幕上。例如在执行下面的 ackermann 函数时。
acker(1,2);
public int acker(int m, int n){
System.out.println("Entered acker");
if(m == 0)
return n + 1;
if(n == 0)
return acker(m-1,1);
return acker(m-1, acker(m, n - 1));
}
当我进入acker方法时我可以打印,但是在该方法完成调用自身后我将如何打印。例如输出将是:
Entered acker
Entered acker
Entered acker
Entered acker
//Here it would say leaving because its not making another recursive call
重构以将 return 值分配给变量,打印您的消息,然后 return 值:
public int acker(int m, int n){
System.out.println("Entered acker");
int result;
if(m == 0)
result = n + 1;
else if(n == 0)
result = acker(m-1,1);
else
result = acker(m-1, acker(m, n - 1));
System.out.println( "Returning " + result + " from acker");
return result;
}