gpt4 book ai didi

java - 调用递归函数如何改变结果?

转载 作者:行者123 更新时间:2023-11-30 10:39:58 26 4
gpt4 key购买 nike

我正在阅读一本名为“思考 Java:如何像计算机科学家一样思考”的书,最近我学习了递归方法。

public static void countdown(int n)
if (n == 0) {
System.out.println("Blastoff!");
} else {
System.out.println(n);
countdown(n - 1);
}
}

这将是一个正常的递归方法,用于倒数到 0,我明白发生了什么,但是如果你像这样在 System.out.println 之前进行递归调用

if (n == 0) {
System.out.println("Blastoff!");
} else {
countup(n - 1);
System.out.println(n);
}

它以相反的方式计数,所以如果我为这两个条件语句给出参数 3,第一个为“3, 2, 1, Blastoff!”但是第二个 1 变成了“Blastoff, 1 ,2 ,3”......我不明白这是怎么回事,有人可以尝试解释这段代码中发生了什么,使它以相反的方式计数吗?

最佳答案

if (n == 0) {
System.out.println("Blastoff!");
} else {
countup(n - 1);
System.out.println(n);
}

那只是因为您将 countdown(n-1) 放在 system.out.println(n); 之前

当你放置在 System.out.println(n) 之前时,该方法将从 countdown(n-1) 继续调用,直到它结束调用和光标转到下一个 system.out.println。

So, that's how a recursion works, its like a self contained method, one method calling another method......finally onces the last method gets finished, its comes back to last-1 and then last-2 and the last-n

在你的例子中,首先它进入 countdown(n-1),并继续调用相同的方法直到它到达,n==0。一旦 n==0,所有方法调用都会返回到它们的 System.out.println(n);

关于java - 调用递归函数如何改变结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39092071/

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