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);
}
}此代码具有以下输出:带有print(3)的YY122333;
不过,我不明白原因。函数为什么要从打印1开始呢?它不是先通过if函数,然后打印Y和实心2吗?
我
发布于 2013-09-24 08:45:51
您创建了一种特殊类型的函数,称为递归函数,这意味着该函数调用自身。
因此,当您第一次调用它时(参数大于1,我猜在您的例子中是3),它会打印Y,然后再次调用print函数作为参数i-1 (2)
因此,它再次进入函数,计算条件,并作为i>1,再次以1作为参数调用自己。
它再次进入内部,但这一次不一样,第一个条件是false,它跳入只打印一次1的for循环。
然后函数被恢复,调用函数将被取回我们离开它的地方(请记住,它是以2作为参数的相同函数)。所以它进入循环,打印两次2,然后继续.
..。以3作为参数的函数的第一次调用。因此,它进入循环,打印三次3。
然后,执行首先恢复到任何称为print函数的函数。
发布于 2013-09-24 08:42:38
这是你的顺序:
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当代码看起来很奇怪时,在Eclipse这样的IDE中使用调试器并观察变量的变化总是很有帮助的。
发布于 2013-09-24 08:43:26
你的算法是递归的。如果在语句中遵循这一逻辑,那么
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. 希望这能有所帮助
https://stackoverflow.com/questions/18976661
复制相似问题