四則運算
教學範例《3》…四則運算

表單設計與程式執行:
表單設計
執行畫面

控制項屬性資料:
Form1 : 調整表單視窗的大小,使Width和Height合乎適當大小。

Label1 : Caption "A="
Label2 : Caption "B="
Label3 : Caption "A+B"
Label4 : Caption "A-B"
Label5 : Caption "A*B"
Label6 : Caption "A/B"
Label7 : Caption "機械系 二年甲班"
Label8 : Caption "王小明 49602099"

Text1: Alignment "2-置中對齊",Text ""
Text2: Alignment "2-置中對齊",Text ""
Text3: Alignment "2-置中對齊",Text ""
Text4: Alignment "2-置中對齊",Text ""
Text5: Alignment "2-置中對齊",Text ""
Text6: Alignment "2-置中對齊",Text ""

Frame1:    Caption "四則運算"
Command1:  Caption "計算"
Command2   Caption "結束"

程式碼列表:
Private Sub Command1_Click()
Dim A, B As Single

A = Val(Text1.Text)
B = Val(Text2.Text)
C1 = A + B
C2 = A - B
C3 = A * B

If B = 0 Then
   MsgBox "除法分母不可為零!", , "錯誤訊息"
   Else
   C4 = A / B
End If

Text3.Text = Str(C1)
Text4.Text = Str(C2)
Text5.Text = Str(C3)

If B = 0 Then
   Text6.Text = "分母為0,錯誤!"
   Else
   Text6.Text = Str(C4)
End If

End Sub

Private Sub Command2_Click()
End
End Sub
程式解說:
學習重點:
 ˙學會由指定的TextBox中讀取數據。
 ˙學會將計算所得的數據放入指定的TextBox中。
 ˙學會使用MsgBox顯示訊息視窗。
 ˙能夠正確的使用If...Then...Else..End If判斷結構。
程式說明:
 (1)首先宣告A,B兩變數為單精度實數,Single。 
 (2)A = Val(Text1.Text) '由文字框1中讀取A值。 
  (3)B = Val(Text2.Text) '由文字框2中讀取B值。
  (4)計算C1,C2,C3分別為加減乘法的結果。
  (5)如果B=0,則分母為零,由判斷式IF顯示錯誤訊息。
     如果B≠0,則Text6.Text = Str(C4)。
  (6)將C1,C2,C3的數值分別轉入文字框3,4,5中。
  (7)如果分母為0,則文字框6顯示"分母為0,錯誤!"。
     否則文字框6顯示C4數值。
  (8)Command2按鈕,僅有一指令"End"為程式結束。