Function factorial(n As Integer) As Double
  Dim t As Double
  If n = 0 Then t = 1 Else t = n * factorial(n - 1)
  factorial = t
End FunctionPrivate Sub Command1_Click()  Label3.Caption = factorial(Text1.Text)
  
End SubPrivate Sub Command2_Click()
  Text1.Text = ""
  Label3.Caption = ""
End Sub估计大家都见过这个程序啊,上面程序是没有问题的,测试过都正确。
我有一点不明白啊,第三行函数反复调用自己,假如我输入的n=3,在函数调用
过程中,最后执行factorial (0),应该执行哪一条语句。是执行n=0,then t=1?

解决方案 »

  1.   

    Function factorial(n As Integer) As Double
    factorial (0)
    就是n=0了递归过程的程序运行方式可能不是你想的样子,你单步跟踪一下,就可以大体知道了。
      

  2.   

    If n = 0 Then t = 1 Else t = n * factorial(n - 1)
    If语句成立,执行then,不成立,执行else,怎么会同时执行?
      

  3.   

    改成下面这样,然后单步走一遍不就明白了吗?
    Function factorial(n As Integer) As Double
      Dim t As Double
      Dim f As Double  If n = 0 Then 
        t = 1 
      Else 
        f = factorial(n - 1)
        t = n * f
      End If
      factorial = t
    End Function