一个函数可以调用自身。 这被称为递归。 以下是使用递归函数计算给定数字的阶乘的示例:
Module myfunctions Function factorial(ByVal num As Integer) As Integer ' local variable declaration */ Dim result As Integer If (num = 1) Then Return 1 Else result = factorial(num - 1) * num Return result End If End Function Sub Main() 'calling the factorial method Console.WriteLine("Factorial of 6 is : {0}", factorial(6)) Console.WriteLine("Factorial of 7 is : {0}", factorial(7)) Console.WriteLine("Factorial of 8 is : {0}", factorial(8)) Console.ReadLine() End Sub End Module
当上述代码被编译和执行时,它产生了以下结果:
Factorial of 6 is: 720 Factorial of 7 is: 5040 Factorial of 8 is: 40320
网站声明:如果转载,请联系本站管理员。否则一切后果自行承担。
添加我为好友,拉您入交流群!
请使用微信扫一扫!