vb求n阶乘表达式

vb求n阶乘表达式,第1张

Public Function N_Multiplication(ByVal n As Long) As Long
'参数n为整数值,函数返回-1则表明参数n有异常,否则正常计算N阶乘
Dim J As Long
N_Multiplication = -1
'函数给定值-1,参数n必须大于等于1且不能为非数字,否则函数返回-1
If (Not IsNumeric(n)) Or (n <= 0) Then'判断n是否为数字且大于等于1
‘如果不满足上述条件则提示出错!
MsgBox("请不要输入非数字或零值!")
'可以省略此句,可利用函数返回数来判定是否有异常,如果函数返回-1则有异常;
Exit Function
Else ’n如果为数字且大于等于1则正常计算
N_Multiplication = 1
For J = 1 To n
N_Multiplication = J N_Multiplication
'正常计算,并返回N阶乘数
Next
End If
End Function

递归法,下面这个是个编写出来的阶乘函数,直接调用就可以了
Private
Function
jiecheng(n
As
Integer)
As
Integer
If
n
=
1
Then
jiecheng
=
1
Else
jiecheng
=
n

jiecheng(n
-
1)
End
If
End
Function

Private Sub Form_Click()
Dim n As Integer, t#, i%
n = InputBox("输入正整数", "阶乘")
t = 1
i = 1
Do While i <= n
t = t i
i = i + 1
Loop
Print n & "!=" & t
End Sub

private
sub
command1_click()
dim
n,
i,
sum
as
integer
n
=
5
'n的初值
sum
=
1
'1做为阶乘的基数,因为乘以任何数都为原数
for
i
=
1
to
n
'从1乘到n,这是阶乘的原理
sum
=
sum

i
next
i
print
sum
'输出结果
end
sub
private
sub
command1_click()
dim
x,
y
as
single
x
=
1
'给x任意的一个初值
if
x
<
0
then
'x小于0的情况
y
=
0
else:
if
x
>=
0
and
x
<
1
then
'0<=x<1的情况
y
=
1
else:
if
x
>=
1
and
x
<
2
then
'1<=x<2的情况
y
=
2
else:
y
=
3
'3
x>=2的情况
end
if
end
if
end
if
print
y
end
sub

Function ft(x As Integer) As Double
ft = x
If x > 1 Then ft = x  ft(x - 1)
End Function
Private Sub Form_Click() '点击窗体运行
MsgBox "10!=" & ft(10)
End Sub

自己编写函数代码:
Private Function 求阶乘(Byval n As Integer) As Long
Dim i As Integer
Dim Fac As Long
Fac = 1
For i = 1 To n
Fac = Fac i
Next i
求阶乘 = Fac
End Function
在你需要求阶乘的地方,调用该函数:
例如:
Dim y As Long
y = 求阶乘(10) '求阶乘(10)将用10调用上面的自定义函数,返回10的阶乘

Private Sub Command1_Click()
Dim a As Long, b As Long, c As Long
a = Val(InputBox("输入a", "提示"))
b = Val(InputBox("输入b", "提示"))
c = Val(InputBox("输入c", "提示"))

Dim r as Long
r=Multiply(a)+Multiply(b)+Multiply(c)
Print r
End Sub
Private Function Multiply(n As Long) As Long
Dim x As Long
Multiply = 1
For x = 1 To n
Multiply = Multiply x
Next
End Function


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/10428696.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-08
下一篇 2023-05-08

发表评论

登录后才能评论

评论列表(0条)

保存