五笔打字通主页
VB程序题:计算 S=1 + 1/2 + 1/4 + 1/7 + 1/11 + 1/16 + 1/22 + 1/29 + …… 当第i项的值<10-4 时结束 VB源码 龚沛曾
提示:
找出规律,第i项的分母是前一项分母加i开始计数。可利用For循环结构的循环控件变量获得项数,当某项达到规定的精度时退出循环。
解题,代码用三种循环方式来求解题目的式子和,在界面上按三个按钮,代码如下:
Private Sub Command1_Click()
Dim i As Long
Dim a As Double
Dim s As Double
Dim stp As Integer
stp = 1
i = 1
Do While True
If 1 / i < 10 ^ -4 Then Exit Do
a = 1 / i
s = s + a
i = i + stp
stp = stp + 1
Loop
Cls
Print s
End Sub
Private Sub Command2_Click()
Dim i As Long
Dim a As Double
Dim s As Double
Dim stp As Integer
stp = 1
i = 1
Do
a = 1 / i
s = s + a
i = i + stp
stp = stp + 1
Loop Until 1 / i < 10 ^ -4
Cls
Print s
End Sub
Private Sub Command3_Click()
Dim i As Long
Dim j As Long
Dim a As Double
Dim s As Double
Dim stp As Integer
stp = 1
i = 1
'10^(-4)=1/10000
For j = 1 To 10000
If 1 / i < 10 ^ -4 Then Exit For
a = 1 / i
s = s + a
i = i + stp
stp = stp + 1
Next j
Cls
Print s
End Sub
运行程序,点击其中一个按钮,运行程序效果图如下:
Visual Basic程序设计教程(第3版) (龚沛曾等编)课后实验源码
来源:济亨网
本文链接:https://wb98.com/post/72.html