Java 递归函数:在函数调用之前/之后打印语句
为什么这两个代码的输出不同 func 1:按预期反向打印序列Java 递归函数:在函数调用之前/之后打印语句,java,Java,为什么这两个代码的输出不同 func 1:按预期反向打印序列 public static void printSeriesInReverse(int n){ if (n > 0){ System.out.println(n); printSeriesInReverse(n-1); } func 2:打印正常系列而不反转 public static void printSeriesInReverse(int n){ if (n > 0){ p
public static void printSeriesInReverse(int n){
if (n > 0){
System.out.println(n);
printSeriesInReverse(n-1);
}
func 2:打印正常系列而不反转
public static void printSeriesInReverse(int n){
if (n > 0){
printSeriesInReverse(n-1);
System.out.println(n);
}
为什么print语句或函数调用先出现会产生如此大的差异?因为它是一个递归函数。假设你用
n=3
调用它
对于第一种情况,您将得到:
printSeriesInReverse(3)
3 > 0 // YES
prints 3
printSeriesInReverse(2)
2 > 0 // YES
prints 2
printSeriesInReverse(1)
1 > 0 // YES
prints 1
printSeriesInReverse(0)
0 > 0 // NO
// End of recursion
printSeriesInReverse(3)
3 > 0 // YES
printSeriesInReverse(2)
2 > 0 // YES
printSeriesInReverse(1)
1 > 0 // YES
printSeriesInReverse(0)
0 > 0 // NO
// End of recursion
prints 1
prints 2
prints 3
最终输出:321
对于第二种情况,您将得到:
printSeriesInReverse(3)
3 > 0 // YES
prints 3
printSeriesInReverse(2)
2 > 0 // YES
prints 2
printSeriesInReverse(1)
1 > 0 // YES
prints 1
printSeriesInReverse(0)
0 > 0 // NO
// End of recursion
printSeriesInReverse(3)
3 > 0 // YES
printSeriesInReverse(2)
2 > 0 // YES
printSeriesInReverse(1)
1 > 0 // YES
printSeriesInReverse(0)
0 > 0 // NO
// End of recursion
prints 1
prints 2
prints 3
最终输出:
123
关于代码是如何工作的,您还不了解什么?我是第一次学习递归,我是编程新手,所以请原谅我不理解简单的“直截了当”的东西。现在很清楚了。在第二个函数中,我正在努力处理print语句。非常感谢。