【发布时间】:2016-08-23 00:08:47
【问题描述】:
我正在阅读一本名为“思考 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 之前进行递归调用
public static void countdown(int n)
{
if (n == 0) {
System.out.println("Blastoff!");
} else {
countdown(n - 1);
System.out.println(n);
}
}
它的计算方式相反,所以如果我为这两个条件语句都给出了参数 3,那么第一个参数是“3, 2, 1, Blastoff!”但是第二个 1 是“Blastoff, 1 ,2 ,3”....我不明白这是如何工作的,有人可以尝试解释这段代码中发生了什么,使它以相反的方式计数吗?
【问题讨论】:
-
为了更好地理解它的工作原理,请将 println 作为第一个方法行。