当前位置: 代码迷 >> J2SE >> ->关于递归的疑惑<解决办法
  详细解决方案

->关于递归的疑惑<解决办法

热度:132   发布时间:2016-04-24 01:32:19.0
---------------->关于递归的疑惑<-----------------
程序段如下:

Java code
public void test1(int i) {    if(i < 3) {            System.out.print(i);            i++;        test1(i);        test1(i);    }}


输出结果:
0122122

请问为什么在输出012之后还会输出2122?

------解决方案--------------------
你调用了两次
test1(i) ;

public void test1(int i) {
if(i < 3) {
System.out.print(i);
i++;
test1(i); //第一次调用这一步 i = 1 ;所以打印 1 ;然后执行test1(2) ;test1(2) ;--122
test1(i); //第一次调用这一步 i = 1 ;所以打印 1 ;然后执行test1(2) ;test1(2) ;--122
}
------解决方案--------------------
已经说的这么清楚了居然还要求解。。。。

你是不是不理解i的取值问题?i是个局部变量,每次递归调用都会生成新的i,他们之间的值没有保持同步的这种关系。

简化下调用过程,看看你能看懂不?
test1(i=0)
---i++;
---test1(i=1)
------i++;
------test1(i=2)
---------i++;
---------test1(i=3) // if没成立,所以没输出
---------test1(i=3) // if没成立,所以没输出
------test1(i=2)
---------i++;
---------test1(i=3) // if没成立,所以没输出
---------test1(i=3) // if没成立,所以没输出
---test1(1)
------i++;
------test1(i=2)
---------i++;
---------test1(i=3) // if没成立,所以没输出
---------test1(i=3) // if没成立,所以没输出
------test1(i=2)
---------i++;
---------test1(i=3) // if没成立,所以没输出
---------test1(i=3) // if没成立,所以没输出

------解决方案--------------------
Java code
public void test1(int i) {    if(i < 3) {            System.out.print(i);//...0            i++;        test1(i);//test(1)...1                   //i++;                   //test(2)...2                     //i++;                     //test(3)...                     //test(3)...                   //test(2)...2                     //i++;                     //test(3)...                     //test(3)...                                             test1(i);//test(1)...1                   //i++;                   //test(2)...2                     //i++;                     //test(3)...                     //test(3)...                   //test(2)...2                     //i++;                     //test(3)...                     //test(3)...             }}希望楼主能看懂。。
  相关解决方案