递归调用C#

本文关键字:调用 递归 | 更新日期: 2023-09-27 18:20:13

大家好,我是一名初学者,如果你愿意,我想知道这些代码是如何工作的,请:)

 class Program
    {
        static void Main(string[] args)
        {
            Hassn hassn = new Hassn();
          Console.WriteLine(Hassn.Factorial(5));
        }
    }
    class Hassn
    {
    public static double Factorial(double val)
        {
            if (val <= 0) return 1;
            return val* Factorial(val - 1); 
        }
    }

递归调用C#

Factorial(5) ->
5 * Factorial(4) ->
5 * 4 * Factorial(3) ->
5 * 4 * 3 * Factorial(2) ->
5 * 4 * 3 * 2 * Factorial(1) ->
5 * 4 * 3 * 2 * 1 * Factorial(0) ->
5 * 4 * 3 * 2 * 1 * 1

编程语言使用"调用堆栈"来跟踪正在调用的函数及其包含的值。每次调用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将从对Factorial(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的每个调用都嵌套在前一个调用中,然后必须组合所有返回值才能得到最终结果。