【原创】VBA(实验26)VBA写阶乘,用3种方法:纯过程,循环函数,递归函数

 

写一个循环过程


Public Sub jieceng1()   '不用循环迭代,用递归怎么写?
b = 1
a = InputBox("请输入1个数字")
For i = 1 To a
    b = b * i
Next i
MsgBox (a & "的阶乘是" & b)

End Sub

 

sub 调用 循环函数

Public a   '必须让a可传递

Sub jieceng2()
a = InputBox("请输入1个数字")
f_jieceng2 (a)
MsgBox (a & "的阶乘是" & f_jieceng2(a))
End Sub



Function f_jieceng2(x)
    f_jieceng2 = 1
    For i = 1 To x
        f_jieceng2 = f_jieceng2 * i
    Next i
End Function

 

sub 调用递归函数

Public a

Sub jieceng3()
a = InputBox("请输入1个数字")
f_jieceng2 (a)
MsgBox (a & "的阶乘是" & f_jieceng3(a))
End Sub



Function f_jieceng3(x)
  If x = 1 Then
     f_jieceng3 = 1
  Else
     f_jieceng3 = f_jieceng3(x - 1) * x
  End If
End Function

 

你可能感兴趣的:(VBA)