[英]Java - Recursion
The following is my adaptation of an AP Computer Science question. 以下是我对AP计算机科学问题的改编。 The book says it should print 00100123 I think it should print 0010012 But the code below actually prints 3132123
这本书说应该打印00100123,我认为应该打印0010012,但是下面的代码实际上可以打印3132123
What is going on? 到底是怎么回事? Also it does not appear to have any stop condition?!
也似乎没有任何停止条件?!
public class Mystery {
public static void main(String[] args) {
int n;
n = 3;
mystery(n);
}
public static void mystery(int n) {
int k;
for (k = 0; k < n; k++) {
mystery(k);
System.out.print(n);
}
}
}
The actual question reads: Consider the following method. 实际的问题是:考虑以下方法。
public void mystery (int n)
{
int k;
for (k=0 ; k < n ; k++)
{
mystery(k);
System.out.print(n);
}
}
What value is returned by the call mystery (3)? 电话谜题(3)返回什么值?
I now understand that the loop forms the stop condition and I think I understand jhamon's comment "last instruction is to print n. n is 3, there is no way it prints only '0010012'" but I don't understand why the book says it should print 00100123. 我现在知道该循环形成了停止条件,并且我想我理解了jhamon的评论“最后一条指令是打印n。n为3,不可能只打印'0010012'”,但是我不明白为什么书说它应该打印00100123。
As Batsheba says I have tried watching the variables while debugging but the book says it should print 00100123. Thanks very much jhamon for the corrected code , so from what I can see the book is wrong? 正如Batsheba所说的那样,我在调试时尝试观察变量,但是书中说它应该显示00100123。 非常感谢jhamon提供的更正代码 ,因此从我看来这本书是错误的吗?
That program cannot print "0". 该程序无法打印“ 0”。 It prints
n
, and if n
is 0 it will never reach the System.out.print(n)
line. 它输出
n
,如果n
为0,它将永远不会到达System.out.print(n)
行。 That line is inside the for
statment with k<n
. 该行在
for
语句内for
其中k<n
。
As others have pointed out in the comments, that condition in the for
loop is also the stop condition. 正如其他人在注释中指出的那样,
for
循环中的条件也是停止条件。 mystery
will recursively call itself n
times. mystery
将递归n
次。 However, in each of these calls, the parameter is smaller. 但是,在每个这些调用中,参数都较小。
(For fun, try changing the condition to k <= n
. Then it will not terminate, because the parameter is smaller or equal ). (为了有趣,请尝试将条件更改为
k <= n
。然后,由于参数小于或等于 ,它不会终止)。
If you change the line to print(k)
, which is what was probably intended, it will indeed print "0010012". 如果将行更改为
print(k)
,这可能是预期的,则实际上将打印“ 0010012”。 Here is an ideone link to show that. 这是一个ideone链接来显示这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.