7.4.1 过程的嵌套调用
在一个过程( Sub 过程或 Function 过程)中调用另一个过程,称为过程的嵌套,如下图。
例 13 :输入参数 n , m ,求组合数 的值。
程序代码:
Private Function fact(x)
p = 1
For i = 1 To x
p = p * i
Next
fact = p
End Function
Private Function comb(n, m)
comb = fact(n) / (fact(m) * fact(n - m))
End Function
Private Sub Command1_Click()
m = Val(Text1(0).Text):n = Val(Text1(1).Text)
If m > n Then
MsgBox " 请保证参数的正确输入!( m 小于 n ) ": Exit Sub
End If
Text2.Text = Format(comb(n, m), "@@@@@@@@@@@")
End Sub
执行结果:
7.4.2 过程的递归调用
在一个过程( Sub 过程或 Function 过程)直接或间接地调用自己本身,即自己调用自己,称为过程的递归调用。
例如,自然数 n 的阶乘可以递归定义为:

例 14 :利用递归计算 n! 。
程序代码:
Private Function fact(n) As Double
If n > 0 Then
fact = n * fact(n - 1)
Else
fact = 1
End If
End Function
Private Sub Text1_KeyPress(KeyAscii As Integer)
Dim n As Integer, m As Double
If KeyAscii = 13 Then
n = Val(Text1.Text)
If n < 0 Or n > 20 Then MsgBox (" 非法数据! "): Exit Sub
m = fact(n)
Text2.Text = Format(m, "!@@@@@@@@@@")
Text1.SetFocus
End If
End Sub
执行结果:
|