【问题标题】:Why do I need to mention the method name? Why not simply (n-1)*n?为什么我需要提及方法名称?为什么不简单地 (n-1)*n?
【发布时间】: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


【解决方案1】:

因为否则它不会再次调用该函数,只会计算n*(n-1)并退出。对于3,这将是3x2=6,实际上等于3!。但是,如果您尝试使用4!,那么您的更改将返回4x3=12,而实际上计算4! 它应该可以计算出4x3x2x1=24

【讨论】:

  • 非常感谢, Plirkee 和其他所有人!在阅读下一页并查看子主题标题后,我意识到了这一点。确实是递归!
【解决方案2】:

答案很简单,因为大多数阶乘算法都是基于递归方法的,也就是说函数调用自己,如果写(n -1) * n它只会乘一次,结果会出错(不是n!)。 有很多关于递归方法以及阶乘具体如何工作的文章。例如阅读这些: https://www.khanacademy.org/computing/computer-science/algorithms/recursive-algorithms/a/recursive-factorial https://introcs.cs.princeton.edu/java/23recursion/

【讨论】:

    猜你喜欢
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    • 2019-11-19
    • 2022-09-26
    • 2020-10-25
    • 1970-01-01
    • 2014-12-02
    • 2020-02-21
    相关资源
    最近更新 更多