编程语言使用“呼叫-stack“来跟踪哪些函数被调用以及它们包含哪些值。每调用一次Factorial
,它都会连同其变量值一起添加到堆栈中。这被称为上下文。因此,调用堆栈看起来像:
Factorial(5)
Factorial(5) * Factorial(4)
Factorial(5) * Factorial(4) * Factorial(3)
Factorial(5) * Factorial(4) * Factorial(3) * Factorial(2)
Factorial(5) * Factorial(4) * Factorial(3) * Factorial(2) * Factorial(1)
Factorial(5) * Factorial(4) * Factorial(3) * Factorial(2) * Factorial(1) * Factorial(0)
在这个阶段,VAL == 0这样1将从调用返回阶乘(0)。这个上下文现在从调用堆栈中“弹出”,并且返回的值在下一个上下文中用于计算值(在本例中为1 * 1),然后返回到下一个上下文(2 *(1 * 1 )):
Factorial(5) * Factorial(4) * Factorial(3) * Factorial(2) * Factorial(1) * 1
Factorial(5) * Factorial(4) * Factorial(3) * Factorial(2) * (1 * 1)
Factorial(5) * Factorial(4) * Factorial(3) * (2 * (1 * 1))
Factorial(5) * Factorial(4) * (3 * (2 * (1 * 1)))
Factorial(5) * (4 * (3 * (2 * (1 * 1))))
(5 * (4 * (3 * (2 * (1 * 1)))))
这是一个非常一般的解释,我只是想为您提供一个替代方案。试着了解,每次调用Factorial
都嵌套在先前的调用中,然后所有返回值必须组合才能得到最终结果。
从这里开始https://en.wikipedia.org/wiki/Recursive_function – Steve
谢谢史蒂夫帮忙,但我不会说英语well.If你可以向我解释这个例子 –