英文:
Why does the output change in a recursive method?
问题
我已经创建了一个像这样的简单递归方法:
public void rec(int a) {
if(a > 0) {
rec(a - 1);
System.out.println(a);
}
}
这个方法的输出结果是:
1
2
3
4
5
这很棒,但问题是,为什么当我将打印命令放在if语句外部时,输出从0开始而不是1?
public void rec(int a) {
if(a > 0) {
rec(a - 1);
}
System.out.println(a);
}
英文:
I have created a simple recursive method like this:
public void rec(int a) {
if(a > 0) {
rec(a - 1);
System.out.println(a);
}
}
the output for this method is:
1
2
3
4
5
And that's just great but the question is why when I write the print command outside the if statement the output starts from 0 not 1?
public void rec(int a) {
if(a > 0) {
rec(a - 1);
}
System.out.println(a);
}
</details>
# 答案1
**得分**: 1
因为,在第一个版本中,`if (a > 0)` 语句阻止了函数打印 `0`。我们可以通过包含两个打印语句来看看这里发生了什么:
```java
public void rec(int a) {
if(a > 0) {
rec(a - 1);
System.out.println("在 if 内部:" + a);
}
System.out.println("在 if 之后:" + a);
}
英文:
> why when I write the print command outside the if statement the output starts from 0 not 1?
Because, in the first version, the if (a > 0)
prevents the function from printing 0
. How about we look at what is happening here by including both prints:
public void rec ( int a) {
if(a>0) {
rec(a-1);
System.out.println("Inside if: " + a);
}
System.out.println("After if: " + a);
}
答案2
得分: 1
在代码中:
public void rec(int a) {
if(a > 0) {
rec(a - 1);
System.out.println(a);
}
}
你递归地调用了方法 rec(),首次方法调用时参数值为 "a",随后的方法调用中参数值为 "a-1"。方法 rec() 中有一个 if 语句,只有在接收到的参数 "a" 的值大于 0 时才会执行。
如果 "a" 的值为 0,则该方法什么都不做,然后返回到调用点,并在该方法范围内打印变量 a 的值。
一个重要的点是,在方法范围内,变量 "a" 的值并未改变,只有传递给下一个方法调用的参数被改变(即 a-1)。
假设初始的方法调用如下:
rec(5) // <-- 方法以 a = 5 被调用
// 方法定义
public void rec(int a) { // <-- a = 5
if(a > 0) { // 5 > 0 ? True
rec(a - 1); // rec(5-1) 即 rec(4),但 a 仍然为 5
System.out.println(a); // <-- 在此方法范围内 a = 5
}
}
要更好地理解,你可以学习作用域、方法和调用栈的相关知识。这将更好地帮助你理解递归。
英文:
In the code
public void rec(int a) {
if(a > 0) {
rec(a - 1);
System.out.println(a);
}
}
you recursively invoke the method rec() with "a" as the parameter value for the first method invocation and then "a-1" for all the subsequent method invocations.<br>
The rec() method has if clause which only executes if the value of parameter "a" received is greater than 0.
if the value of "a" is 0 then the method simply does nothing and returns back to invoking point and prints the value of variable a in that method scope.
An important point is that the value of "a" in a method scope is not being altered only the parameter to the next method call is being altered (i.e a-1)
Let' say the initial method call is something like
rec(5) // <-- method invoked with a = 5
//method definition
public void rec(int a) { // <-- a = 5
if(a > 0) { // 5 > 0 ? True
rec(a - 1); // rec(5-1) ie rec(4) but a = 5 still
System.out.println(a); // <-- a = 5 in this method scope
}
}
To have a better idea you can read on scopes,methods and call Stacks.
This will give a better grasp on recursion as well.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论