vb求阶乘程序问题
来源:百度知道 编辑:UC知道 时间:2024/07/04 23:19:38
哪位高手能帮我看一下下面这个求阶乘程序为什么计算结果不正确?
我错了····
Private Sub Command1_Click()
Dim a As Integer
a = Int(Val(Text1.Text))
Text2.Text = jiec(a)
End Sub
Private Sub Command2_Click()
End
End Sub
Private Function jiec(ByVal n As Integer) As Long
Dim i As Integer
jiec = 1
If n = 0 Or n = 1 Then
Exit Function
Else
For i = 1 To n
jiec = jiec * n
Next i
End If
End Function
我错了····
Private Sub Command1_Click()
Dim a As Integer
a = Int(Val(Text1.Text))
Text2.Text = jiec(a)
End Sub
Private Sub Command2_Click()
End
End Sub
Private Function jiec(ByVal n As Integer) As Long
Dim i As Integer
jiec = 1
If n = 0 Or n = 1 Then
Exit Function
Else
For i = 1 To n
jiec = jiec * n
Next i
End If
End Function
程序呢,请补充一下吧
Option Explicit
Private Sub Command1_Click()
Dim a As Integer
a = Int(Val(Text1.Text))
Text2.Text = jiec(a)
End Sub
Private Function jiec(n As Integer) As Long
If n = 0 Then
jiec = 1
Else
jiec = n * jiec(n - 1)
End If
End Function
这样就可以了!
松松一号 的方法很好了。
不过,既然jiec() As Long 定义为Long类型,最好限制一下n值的大小,否则造成数据超限的不必要麻烦。
你的计算公式写错了,应该为
For i = 1 To n
jiec = jiec * i
Next i
你原来的方法算出来应该是n的n次方
而不是n的阶乘
另外n=0,1的时候你要给出他们的阶乘。要不返回的都是0