退出递归调用后如何在屏幕上打印。例如,在做如下的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
最佳答案
重构以将返回值分配给变量,打印消息,然后返回值:
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;
}
关于java - 离开递归调用后如何打印,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28846108/