gpt4 book ai didi

java - 有人可以解释这个程序的控制流程吗?

转载 作者:搜寻专家 更新时间:2023-10-31 19:44:38 25 4
gpt4 key购买 nike

这是我的 AP 计算机科学类(class)中的示例程序,我无法理解它的控制流程。

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

任何人都可以帮助学生并向我解释它是如何输出它做了什么的吗?

最佳答案

当函数完成时,调用它的函数有机会完成并执行更多代码。

这是递归如何发生的说明。递归的每个级别都由缩进的增加表示。

mystery(5):
"mystery called with n = 5"
mystery(4):
"mystery called with n = 4"
mystery(3):
"mystery called with n = 3"
mystery(2):
"mystery called with n = 2"
mystery(1):
"mystery called with n = 1"
mystery(0):
"mystery called with n = 0"
"n is zero so no more recursive calls!"
mystery(0) returns
"We did it again with n = 1"
end of mystery(1)
"We did it again with n = 2"
end of mystery(2)
"We did it again with n = 3"
end of mystery(3)
"We did it again with n = 4"
end of mystery(4)
"We did it again with n = 5"
end of mystery(5)

关于java - 有人可以解释这个程序的控制流程吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35246277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com