本文介绍了请逐步解释递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请逐步解释递归;
public class TestClass {
private static void printit(int i) {
if (i == 1) {
return;
}
System.out.println(i);
printit(i / 2);
printit(i / 2);
}
public static void main(String args[]) {
int i = 8;
printit(i);
}
}
推荐答案
如果你正在使用IDE,你可以使用调试器,亲眼看看一步一步发生了什么。
If you're using IDE you can just use the debugger and see with you own eyes what's happening step by step.
无论如何,让我们尝试一下当我们调用递归时会发生什么方法:
你用8调用方法( printit(8);
):
Anyway, let's try and what happens when we call the recursive method:You call the method with 8 (printit(8);
):
-
System.out.println(8);
- > 8 -
printit(8 / 2);
- >再次调用方法,8/2 = 4 -
System.out.println(4);
- > 4 -
printit(4/2);
>再次调用方法,4/2 = 2 -
System.out.println(2);
- > 2 -
printit(2/2);
>>再次拨打方法,2/2 = 1 -
return;
- >继续之前的通话,(printit(4/2);
) -
printit(2/2);
>>再次调用方法,2/2 = 1 -
return;
- >继续以前呼叫,(printit(4/2);
) - 方法结束,继续前一次呼叫(
printit(8/2);
) -
printit(4/2);
>致电方法再次使用4/2 = 2 -
System.out.println(2);
- > 2 - 调用
printit(2/2);
我们已经知道什么都没有。 - 现在我们在再次打电话,
printit(8);
,要求printit(8/2);
-
System.out.println(4);
- > 4 - 16等...
System.out.println(8);
-> 8printit(8 /2 );
-> Call to method again with 8/2=4System.out.println(4);
-> 4printit(4 /2 );
> Call to method again with 4/2=2System.out.println(2);
-> 2printit(2 /2 );
> Call to method again with 2/2=1return;
-> Continues with previous call, the (printit(4 /2);
)printit(2 /2 );
> Call to method again with 2/2=1return;
-> Continues with previous call, the (printit(4 /2);
)- method finishes, continues with the previous call (
printit(8 /2);
) printit(4 /2 );
> Call to method again with 4/2=2System.out.println(2);
-> 2- calls
printit(2/2);
which we already know result in nothing. - Now we are in the first call again, the
printit(8);
, calling forprintit(8/2);
System.out.println(4);
-> 4- 16 etc...
这篇关于请逐步解释递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!