VB题目s=1-1/2!+1/3!-1/4!+...-1/n!≈ 要求用do loop
1个回答
展开全部
通用求阶乘的参考代码:
Public Function MyFunc(ByVal AddFrom As Long, _
ByVal AddTo As Long) As Single
If AddFrom < AddTo Then
MyFunc = AddFrom * MyFunc(AddFrom + 1, AddTo)
Else
MyFunc = AddFrom
End If
End Function
Form_Load 代码(Do...Loop Until):
Private Sub Form_Load()
Dim lngAddFrom As Long
Dim lngAddTo As Long
Dim lngLoop As Long
Dim sngResult As Single
lngAddFrom = 1
lngAddTo = 5
Do
lngLoop = lngLoop + 1
sngResult = sngResult + (-1) ^ (lngLoop + 1) * 1 / MyFunc(lngAddFrom, lngLoop)
Loop Until lngLoop = lngAddTo
Print "1/1!-1/2!+1/3!-1/4!+1/5!≈" & CStr(FormatNumber(sngResult, 4, vbTrue))
End Sub
Form_Load 代码(For...Next):
Private Sub Form_Load()
Dim lngAddFrom As Long
Dim lngAddTo As Long
Dim lngLoop As Long
Dim sngResult As Single
lngAddFrom = 1
lngAddTo = 5
For lngLoop = lngAddFrom To lngAddTo
sngResult = sngResult + (-1) ^ (lngLoop + 1) * 1 / MyFunc(lngAddFrom, lngLoop)
Next
Print "1/1!-1/2!+1/3!-1/4!+1/5!≈" & CStr(FormatNumber(sngResult, 4, vbTrue))
End Sub
上述两种方法演示了求出 n = 5 的结果:
1/1!-1/2!+1/3!-1/4!+1/5!≈0.6333
实际使用时可以修改 lngAddTo 参数
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询