主题:[讨论]1到10的阶乘的两种算法为什么结果不一样?欢迎回帖。。
方法一:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer
Dim s As Long
Dim p As Long
p = 1
For i = 1 To 10
p = p * i
s = s + p
Next
TextBox1.Text = "1!+2!+...+10!=" & p.ToString
方法二:递归
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer
Dim s As Long
For i = 1 To 10
s = s + fac(i)
Next
TextBox1.Text = "1!+2!+...+10!=" & s
End Sub
Private Function fac(ByVal i As Integer) As Long
Dim s As Long
If i > 1 Then
s = i * fac(i - 1)
Else
s = 1
End If
fac = s
End Function
End Class
End Sub