VB 用自定义函数(function),求1!+2!+3!+…+10!并用print显示结果?

来源:百度知道 编辑:UC知道 时间:2024/06/10 00:47:05
一定要在VB里求:

用自定义函数(function),求1!+2!+3!+…+10!并用print显示结果?
Private Sub Command1_click()

End Sub
function fact(x as integer) as long

end function

Private Sub Command1_click()
dim i as integer
dim sum as long
for i=1 to 10
sum=sum+fact(i)
next
debug.print sum
End Sub

function fact(x as integer) as long
if x=1 then
fact=1
else
fact=x*fact(x-1)
end if
end function

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
虽然这样写结构清晰,但运算量大,算阶乘的时候一共要乘45次

完全可以改成
Private Sub Command1_click()
dim i as integer
dim jie as long
dim sum as long
jie=1
for i=1 to 10
jie=jie*i
sum=sum+jie
next
debug.print sum
End Sub

这样算所有阶乘一共只需要乘10次

ps: 乘法要比加法浪费多的多的CPU时间

找一个现成的

Private Sub Command1_Click()
n = InputBox("输入自然数", "输入")
JieCheng n
If n > 1 Then
For j = n To 2 Step -1
Print j & "*";
Next j
End If
Print "1=";
Print JieCheng(n)
End Sub

Private