问题
When I run this piece of code for n=5 the output I get is "5 3 1 1 3 5"
I get the 5 3 1 part but after that n=-1 but when I run the code with a debugger it when n=-1 it goes to the line after numbers(n-2);
i.e System.out.prt(n+ "");
even though that statement is contained in the if block.
Why does this happen?
public void numbers(int n)
{
if(n>0)
{
System.out.print(n+" ");
numbers(n-2);
System.out.print(n+" ");
}
}
TLDR : when n=-1 System.out.prt(n+ "");
even though it is within the if block which only runs when n>0.
Any help would be much appreciated. Thanks in advance!
回答1:
Here is what happens behind the scenes, for n == 5
:
numbers(5);
if(5 > 0)--> true :
System.out.print(5 + " "); // (1)
numbers(3);
| if(3 > 0)--> true :
| System.out.print(3 + " "); // (2)
| numbers(1);
| | if(1 > 0)--> true :
| | System.out.print(1 + " "); // (3)
| | numbers(-1);
| | System.out.print(1 + " "); // (4)
| System.out.print(3 + " "); // (5)
System.out.print(5 + " "); // (6)
Notice how each number is supposed to be printed twice:
System.out.print(n + " "); // print once
numbers(n-2);
System.out.print(n + " "); // print twice
回答2:
Remove the final System.out.print(n+" "); After the recursive numbers call it comes back with the original value for n and prints this again.
It bubbles back from the deepest level where it prints 1 two times up to the call with number 3, which is printed again, and also 5 is printed again.
If you want it to update the value after it is printed the first time you will have to update the variable n by performing n-=2 instead of n-2
回答3:
5 first system.out then number(5-2)
|
----> 3 first system.out then number(5-2)
|
----->1 first system.out then number(5-2)
(smaller than 0) , returning
|
1 second system.out
|
3<---- second system.out
|
5<--------- second system.out
回答4:
after n=-1, the recursive call will end and return back to the caller method to continue. first commands it found is print.
If you try to debug with the debugger, you will see how rational it is.
回答5:
Java maintain method call into stack and as first 5,3,1 gets printed after which method call resume execution for remaining calls and prints 1,3,5 from stack(last call in stack get's picked up first).
回答6:
Follow the recursion stack.
stack representation with and output flow:
------------------------->
5 3 1
num(5)--> num(3) --> num(1) --> num(-1) --> void
5 3 1
<-------------------------
Now since numbers(-1) does not satisfy the if condition, the program control comes out of the if block, and returns void. Start popping out the stack now (recursion): 5 3 1 1 3 5. That's what the output you get, and is expected.
来源:https://stackoverflow.com/questions/34725881/how-does-this-recursive-function-get-to-this-output