第四章  选择结构设计
双击滚屏  关闭窗口

 

4.6 程序举例



[ 例 4.10] 设计一个电子倒计时器。先由用户给定倒计时的初始分秒数,然后开始倒计时,当计到 0 分 0 秒时,通过消息对话框显示“倒计时结束”。

( 1 )创建应用程序用户界面和设置对象属性。 如图 4.10 所示。


图 4.10 电子倒计时器的设计界面

(2) 编写程序代码如下:

Dim m As Integer, s As Integer

Private Sub Form_Load()

Timer1.Interval = 1000

Timer1.Enabled = False

End Sub

Private Sub Command1_Click()

m = Val(Text1.Text)

s = Val(Text2.Text)

Timer1.Enabled = True

End Sub

Private Sub Timer1_Timer()

If s > 0 Then

s = s - 1

Else

If m > 0 Then

m = m - 1

s = 59

End If

End If

Text1.Text = Format(m, "00")

Text2.Text = Format(s, "00")

If s = 0 And m = 0 Then

Beep

MsgBox " 计时结束! "

End

End If

End Sub

[ 例 4.11] 设计程序,输入两个运算数和运算符( + , - , * , / ),组成算式并计算结果,然后显示出来。

( 1 )创建应用程序用户界面和设置对象属性。 如图 4.11 所示。


图 4.11 例 4.11 的运行结果

(2) 编写程序代码如下:

Private Sub Form_Load()

Option1.Value = True

End Sub

Private Sub Command1_Click()

Dim a As Single, b As Single, t As Single, s As String

a = Val(Text1.Text)

b = Val(Text2.Text)

Select Case True

Case Option1.Value

s = "+"

t = a + b

Case Option2.Value

s = "-"

t = a - b

Case Option3.Value

s = "*"

t = a * b

Case Option4.Value

s = "/"

t = a / b

End Select

Text3.Text = a & s & b & "=" & t

End Sub

Private Sub Command2_Click()

Text1.Text = ""

Text1.Text = ""

Text1.Text = ""

End Sub

Private Sub Command3_Click()

End

End Sub

[ 例 4.12] 计算一元二次方程 的根。

              



图 4.12 例 4.12 的程序流程图

( 1 )创建应用程序用户界面和设置对象属性。 如图 4.13 所示。


图 4.13 例 4.12 的运行结果

(2) 编写程序代码如下:

Private Sub Command1_Click()

Dim a As Single, b As Single, c As Single

Dim x1 As Single, x2 As Single

Dim r As Single, p As Single

a = Val(Text1.Text)

b = Val(Text2.Text)

c = Val(Text3.Text)

If a = 0 Then

Text4.Text = " 不是二次方程 "

Text5.Text = " 不是二次方程 "

Else

d = b * b - 4 * a * c

r = -b / (2 * a)

If d = 0 Then

Text4.Text = r

Text5.Text = r

ElseIf d > 0 Then

x1 = (-b + Sqr(d)) / (2 * a)

x2 = (-b - Sqr(d)) / (2 * a)

Text4.Text = x1

Text5.Text = x2

Else

p = Sqr(-d) / (2 * a)

Text4.Text = r & "+" & p & "i"

Text5.Text = r & "-" & p & "i"

End If

End If

End Sub

 
双击滚屏  关闭窗口
 
版权所有数学与信息科学学院