Java 为什么这个递归方法被认为是阶乘?

Java 为什么这个递归方法被认为是阶乘?,java,recursion,Java,Recursion,直到m=1和n=1之前,我都理解这种方法所做的一切。当m=1和n=1时,if()之后发生的事情是有问题的 public class exc { public static void main(String[] args) { System.out.println(prod(1, 4)); } public static int prod(int m, int n) { if (m == n) { return

直到
m=1
n=1
之前,我都理解这种方法所做的一切。当
m=1
n=1
时,
if()
之后发生的事情是有问题的

public class exc {

    public static void main(String[] args) {
        System.out.println(prod(1, 4));
    }

    public static int prod(int m, int n) {

        if (m == n) {
            return n;

        } else {
            int recurse = prod(m, n - 1);                       

            int result = n * recurse;       // how n gets its value here?
            return result;

        }
    }
}
  • 递归的值是什么?我的意思是prod如何只产生一个 整数(因为它有两个整数)

  • 在if中,当m=1和n=1时,返回值为1,那么为什么程序不在此终止?相反,它在“返回结果”之后终止;在其他情况下

  • 在m=1和n=1之后,n为2(递归);如何将n设置为2?是不是因为2还在记忆中,必须处理

  • 我查过了


    我还在不同的行之后使用println来查看输出,但这也没有帮助。我还使用了调试器。

    当m=1时,程序返回阶乘。 举个例子:(m=1,n=4)


    每次递归调用函数prod时,当前函数prodA都会暂停(将其变量的值保存在内存中)以执行新函数prodB,直到prodB向prodA返回某些内容为止。然后A继续执行自身(从内存中加载其值)

    在调试中运行该程序怎么样?它被视为“阶乘”,因为它是。不清楚你在问什么。可能是重复的,让
    n
    的值小于
    m
    ,让乐趣开始吧@progy_rock,这不会持续很长时间,堆栈溢出错误会很快发生。
    4 != 1 -> so you call recursively prod(1, 3) 
        3 != 1 -> so you call recursively prod(1, 2)
            2 != 1 -> so you call recursively prod(1, 1)
                1 == 1 -> you return 1 to the last call
            In this call, recurse = 1 and n = 2 so you return 2 to the upper call
        Here, recurse = 2, n = 3, so you return 6 to the upper call
    Here, recurse = 6, n = 4, so you return 24 to the upper call
    
    END OF FUNCTION, result is 24 which is 4!