这是我的AP计算机科学课程中的示例程序,我无法理解它的控制流程。
public static void mystery( int n )
{
System.out.println( "mystery called with n = " + n );
if ( n == 0 )
{
System.out.println( "n is zero so no more recursive calls!" );
return;
}
mystery( n - 1 );
System.out.println( "We did it again with n = " + n );
}
public static void main( String[] args )
{
mystery( 5 );
}
它输出以下内容:
mystery called with n = 5
mystery called with n = 4
mystery called with n = 3
mystery called with n = 2
mystery called with n = 1
mystery called with n = 0
n is zero so no more recursive calls!
We did it again with n = 1
We did it again with n = 2
We did it again with n = 3
We did it again with n = 4
We did it again with n = 5
到目前为止,我了解递归方法以及它如何通过以下方式调用自身:
mystery( n - 1 );
但是,我看不到它如何在输出以下五个语句后输出:
n is zero so no more recursive calls!
从逻辑上讲,似乎只会声明:
We did it again with n = 0
谁能帮助学生并向我解释它如何输出结果?
在“ n为零”之后,不再需要递归调用!该方法继续(状态被放在堆栈上,然后在对method(n-1)的调用完成后加载。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句