用VB編寫計算器(轉載)
一.實驗目的
用vb語言編寫一個簡易計算器
二.實驗要求
1.能夠完成浮點數(shù)的加,減,乘,除;(平方等)
2.能夠實現(xiàn)退格和清除功能;
3.初始值為0.0;
4.小數(shù)點不能重復輸入;
5.高位數(shù)的0不出現(xiàn);
6.應用控件數(shù)組實現(xiàn)。
三.控件屬性列表
1、創(chuàng)建控件組的方法
a、首先創(chuàng)建一個命令按鈕,調整其大小 — 寬、高為 495,名稱為Command1,aption 屬性為數(shù)字 0 。
b、然后進行“復制”和“粘貼”,當選擇“粘貼”時,出現(xiàn)對話框提示已有一個同名控件,詢問是否創(chuàng)建控件組,選擇“是”后,即創(chuàng)建了一個名為“Command”的控件組。這時,第一個按鈕的Index屬性值默認為“0”,第二個的Index屬性值自動設為“1”,并且大小與第一個按鈕相同,只需修改其 Caption 屬性為數(shù)字“1”并將其拖至合適位置即可。此后繼續(xù)使用“粘貼”的方法建立其他控件組中其余按鈕,共19個按鈕,每建立一個,就將它拖到合適處,并修改相應的Caption屬性值。
c、建立其他控件:如右圖所示
2、各控件屬性設置如下:
控 件 控 件
控件 名稱 Caption 控件 名稱 Caption
窗體 Form 1 計算器 按鈕 Command 2(0) +
按鈕 Command 3 退格 按鈕 Command 2(1) -
按鈕 Command 4 . 按鈕 Command 2(2) #61624;*
按鈕 Command 5 = 按鈕 Command 2(3) /
按鈕 command 6 + 按鈕 Command 7 ±
按鈕 Command 1(0)~Command1(9) Caption 0 ~ 9
各個屬性修改后得到如圖所示的界面
四 程序如下
Dim shu1 As Single, shu2 As Single, suanfu As String
’定義兩個單精度數(shù)變量用與存放參與運算的數(shù),一個字符型存放運算符
Private Sub Command1_Click(Index As Integer)
Text1.Text = Text1.Text Command1(Index).Caption
’將command1的單擊事件與文本框顯示的內容連接
End Sub
Private Sub Command2_Click(Index As Integer)
shu1 = Val(Text1.Text) ’將shu1隱藏起來
suanfu = Command2(Index).Caption
Text1.Text = ""
End Sub
Private Sub Command4_Click()
Text1.Text = Text1.Text + "."
If (InStr(Text1.Text, ".") = 1) Then ’第一位不能為小數(shù)
Text1.Text = ""
End If
If InStr(Text1.Text, ".") Len(Text1.Text) Then
’防止出現(xiàn)兩個小數(shù)點
Text1.Text = Left(Text1.Text, Len(Text1.Text) - 1)
End If
End Sub
Private Sub Command5_Click() ’開始加減乘除的運算
shu2 = Val(Text1.Text)
Select Case suanfu
Case "+"
Text1.Text = shu1 + shu2
Case "-"
Text1.Text = shu1 - shu2
Case "*"
Text1.Text = shu1 * shu2
Case "/"
If shu2 = 0 Then
MsgBox "分母不能為零!", 1 + 32 + 0,
"錯誤" ’錯誤提示框圖下所示
Text1.Text = ""
Else
Text1.Text = shu1 / shu2
End If
End Select
End Sub
Private Sub Command3_Click() ’假如輸入錯誤,可每次退后一格
If Text1.Text = "" Then
Exit Sub
End If
Text1.Text = Left(Text1.Text, Len(Text1.Text) - 1)
End Sub
Private Sub Command6_Click()
Text1.Text = "" ’清除
End Sub
Private Sub Command7_Click() ’平方運算
Text1.Text = Text1.Text * Text1.Text
End Sub
Private Sub Command8_Click()
If Left(Text1.Text, 1) "-" Then
Text1.Text = "-" Text1.Text
Else
Text1.Text = Right(Text1.Text, Len(Text1.Text) - 1)
End If
End Sub
021yin.com 交流