【发布时间】:2018-02-28 18:29:00
【问题描述】:
这是示例代码,我在 Java The Complete reference, 9th edition 中遇到过。
// A simple example of recursion.
class Factorial { // this is a recursive method
int fact(int n) {
int result;
if(n==1) return 1;
result = fact(n-1) * n; //This is my question, why not just (n-1)*n?
return result;
} }
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3)); //
} }
【问题讨论】:
-
(n-1) * n将计算,嗯,(n-1) * n,这不是 n 的阶乘。 -
递归计算值。在函数内调用相同的函数。
-
只写 (n-1)*n 将执行一次并给出错误的输出。我们需要递归调用,所以我们在那里调用相同的函数
-
是的,如果你总是只通过 3,那么你的问题是对的。尝试通过 4,现在你就会明白为什么需要调用
fact(n-1)*n而不是(n-1)*n -
我建议你尝试一下,看看有什么不同。如果您不确定为什么会有所不同,您可以在调试器中单步调试代码。
标签: java