我在MSDN文档中找到了这段代码作为递归函数的示例:链接如下:
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的第一部分应该调用语句I中的阶乘函数,并发送参数n-1 = 4,这就是我的第一个问题:当我们从语句II调用语句I中的阶乘函数,并传递等于4的参数(n-1)时,我们也将其乘以n....what,我们在语句II中返回吗?换句话说,有人能以一步一步的方式解释阶乘价值是如何计算的吗?
另外,我试着用这段代码来写一个完整的程序,但不幸的是我不能让它工作。为了让它工作,我必须在Factorial函数中引入第二个参数-一个实际存储计算值的参数。我已经提供了下面的代码。我的第二个问题是:有没有可能简化代码,我的想法是不使用第二个参数“written...the”...Is来实现呢?
我写的代码如下:
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发布于 2020-09-27 22:46:00
给定递归函数:
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,然后我们“展开”并在调用链中向后移动,将返回值替换到递归调用所在的前一行中。在展开过程中的每个点,都会计算(并返回)一个新的整数值,直到我们最终得到由原始递归调用返回的最终答案,并将其赋给"result“变量:
Return 1
Return 2 ' 1 * 2
Return 6 ' 2 * 3
Return 24 ' 6 * 4
Return 120 ' 24 * 5发布于 2020-09-28 04:58:51
如果你只对学习递归是如何工作的感兴趣,那么Idle_Mind的答案是不错的。然而,如果你只想计算一个数的阶乘,这就简单多了:
Dim Factorial As Integer = 1
For i As Integer = 1 To N
Factorial *= i
Next其中N是阶乘所需的数字。
https://stackoverflow.com/questions/64088324
复制相似问题