首页 > 解决方案 > 在 VB.net 中使用递归函数

问题描述

我在 MSDN 文档中找到了这段代码作为递归函数的示例:下面提供了链接:

https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/recursive-procedures

Function Factorial(n As Integer) As Integer ......'statement 1
    If n <= 1 Then
        Return 1
    End If
    **Return Factorial(n - 1) * n** 'Statement II: Not understanding how this helps calculating the factorial
End Function

虽然我确实了解递归函数的工作原理,但我不明白语句 II 是如何计算阶乘的。例如,假设我们在第一步中输入 n =5。然后根据我的理解,语句 II 的第一部分将在语句 IReturn **Factorial(n - 1)**中调用 Factorial 函数并发送参数 n-1 = 4。这就是我的第一个问题是:当我们从语句中调用语句 I 中的 Factorial 函数时II 并传递等于 4 的参数 (n-1),我们也将它乘以 n....我们在语句 II...中返回的究竟是什么?换句话说,有人可以逐步解释阶乘值是如何计算的吗?

我也尝试使用这段代码编写一个完整的程序,但不幸的是我无法让它工作。为了使它工作,我必须在 Factorial 函数中引入第二个参数——一个实际存储计算值的参数。我提供了下面的代码。我的第二个问题是:是否可以简化我编写的代码......这个想法是不使用第二个参数“fact”......这可能吗?

我写的代码如下:

Module Module1
    Sub Main()
        Dim number As Integer
        Dim fact As Integer = 1
        Console.Write("Please enter number: ")
        number = Console.ReadLine()
        Factorial(number, fact)
        Console.ReadLine()
    End Sub
    Function Factorial(ByVal n As Integer, ByVal fact As Integer) As Integer
        If n > 0 Then
            Console.WriteLine("Current Value of n = {0}", n)
        End If

        If n < 1 Then
            Console.WriteLine("Factorial = {0}", fact)
            Return 1
        End If
        fact = fact * n
        Return Factorial(n - 1, fact)
    End Function
End Module

标签: vb.net

解决方案


给定递归函数:

Function Factorial(n As Integer) As Integer
    If n <= 1 Then
        Return 1
    End If
    Return Factorial(n - 1) * n
End Function

以及值为 5 的初始调用:

Dim result As Integer = Factorial(5)

你会得到这个序列:

Call    What gets returned
----    -----------------------
F(5)    Return Factorial(4) * 5
F(4)    Return Factorial(3) * 4
F(3)    Return Factorial(2) * 3
F(2)    Return Factorial(1) * 2
F(1)    Return 1

当我们到达 F(1) 时,我们返回一个 1,然后我们“展开”并向后移动调用链,将返回值代入递归调用所在的前一行。在展开期间的每一点,都会计算(并返回)一个新的整数值,直到我们最终得到由原始递归调用返回并分配给“结果”变量的最终答案:

Return 1
Return 2 ' 1 * 2
Return 6 ' 2 * 3
Return 24 ' 6 * 4
Return 120 ' 24 * 5

推荐阅读