static void print(int i){
if( i > 1){
System.out.print("Y");
print(i-1);
}
for(int t = 0; t < i ; t++){
System.out.print(i);
}
}
此代码具有以下输出;带打印YY122333(3(;
但是,我不明白为什么。为什么该函数无论如何都会从打印 1 开始?它不是先传递 if 函数然后打印一个 Y 然后是一个实心 2 吗?
米
你的 algrothym 是递归的。如果你在语句中遵循这个逻辑,你有
static void print(int i){
if( i > 1){
System.out.print("Y");
print(i-1);
}
for(int t = 0; t < i ; t++){
System.out.print(i);
}
}
Call print(i==3)
i > 1 -> TRUE
Prints Y
Call print (i==2)
i > 1 -> TRUE
Prints Y
Call print (i==1)
i > 1 -> FALSE
t = 0, t < 1 -> true
print 0
t = 1, t < 1 -> false
return
t = 0, t < 2 -> true
print 0
t = 1, t < 2 -> true
print 1
t = 2, t < 2 -> false
return
t = 0, t < 3 ->
and so on.
希望这有帮助
这是你的序列:
i = 3, call print(3-1)
i = 2, call print(2-1)
i = 1, don't call print as 1 > 1 == False
for (int t=0; t<1; t++) prints '1'
for (int t=0; t<2; t++) prints '2' two times
for (int t=0; t<3; t++) prints '3' three times
当代码看起来很奇怪时,在 IDE (如 Eclipse(中使用调试器逐步执行它总是有帮助的,并观察变量的变化。
你做了一个特殊类型的函数,称为递归函数,意思是函数调用自身。
所以你第一次调用它(参数大于 1,我想在你的例子中是 3(,它会打印Y
然后再次调用 print
函数
i-1 (2)
因此,它再次进入函数,评估条件,并且i>1
,这次再次调用自身,1
作为参数。
再次进入,但这次不同,第一个条件是假的,它跳入一次打印1
的 for 循环中。
然后函数恢复,调用函数将被带回我们离开它的地方(你记住,它是同一个函数,以 2 作为参数(。所以它进入循环,打印2
两次并恢复......
。以 3 作为参数的函数的第一次调用。所以它进入循环并打印3
三次。
然后执行恢复到首先称为print
函数的任何函数
不,代码具有递归调用。函数在函数体中调用自身:print(i-1)
不,它不会。这称为递归。当它找到一个参数i > 1
时,它会调用自己,等待该方法完成(打印其他所有内容(,然后继续。
Iteration Step info Output
1 enter print function i==3
1 if (i>1) 3 > 1 == true
1 System.out.print("Y") Y
1 call print functin with i-1 i - 1 == 2
2 enter print function i==2
2 if (i>2) 2 > 1 == true
2 System.out.print("Y") YY
2 call print function with i-1 i - 1 == 1
3 enter print function i==1
3 if (i>1) 1 > 1 == false
3 for (t=0; t<i; t++) t==0; 0 < 1 == true
3 System.out.print(i) YY1
3 for (t=0; t<i; t++) t==1; 1 < 1 == false
3 end iteration
2 for (t=0; t<i; t++) t==0; 0 < 2 == true
2 System.out.print(i) YY12
2 for (t=0; t<i; t++) t==1; 1 < 2 == true
2 System.out.print(i) YY122
2 for (t=0; t<i; t++) t==2; 2 < 2 == false
2 end iteration
1 for (t=0; t<i; t++) t==0; 0 < 3 == true
1 System.out.print(i) YY1223
1 for (t=0; t<i; t++) t==1; 1<3 == true
1 System.out.print(i) YY12233
1 for (t=0; t<i; t++) t==2; 2<3 == true
1 System.out.print(i) YY122333
1 for (t=0; t<i; t++) t==3; 3<3 == false
1 end iteration