作业帮 > 综合 > 作业

3 .编写一个简易计算器,能进行加减乘除运算,并且能清除运算结果,有加 减 乘除 ,清除一共5个按钮,三

来源:学生作业帮 编辑:作业帮 分类:综合作业 时间:2024/05/08 10:54:47
3 .编写一个简易计算器,能进行加减乘除运算,并且能清除运算结果,有加 减 乘除 ,清除一共5个按钮,三
我写的这段代码,有很多不严谨的地方,大体思路就是这样的
如果用多个文本框来输入的话,很容易实现,配合ComboBox进行运算法则的选择,就更简单了
Dim a As Double, b As Double, x As String
Private Sub Command1_Click(Index As Integer)'控件数组
If Text3.Text <> "" And IsNumeric(Text3.Text) = True Then
                       '文本框不为空,并且输入的是数字
Select Case Index      '判断按下了 控件数组中的哪个键
Case 0
a = Text3.Text
x = "+"                '用变量x来存储要进行的计算类型
Label1.Caption = a & x '用标签显示输入结果
Text3.Text = "0"
Text3.SetFocus
Text3.SelStart = 0               '文本框接受焦点,并且文本
Text3.SelLength = Len(Text3.Text) '为选定状态,方便输入
Case 1
a = Text3.Text
x = "-"
Label1.Caption = a & x
Text3.Text = "0"
Text3.SetFocus
Text3.SelStart = 0
Text3.SelLength = Len(Text3.Text)
Case 2
a = Text3.Text
x = "*"
Label1.Caption = a & x
Text3.Text = "0"
Text3.SetFocus
Text3.SelStart = 0
Text3.SelLength = Len(Text3.Text)
Case 3
a = Text3.Text
x = "/"
Label1.Caption = a & x
Text3.Text = "0"
Text3.SetFocus
Text3.SelStart = 0
Text3.SelLength = Len(Text3.Text)
Case 4
Text3.Text = ""
Label1.Caption = ""
Text3.SetFocus
a = b = c = 0
End Select
Else
Label1.Caption = "只允许输入数字"
End If
End Sub
Private Sub Command2_Click() '用按键“=”,输出最后结果
b = Text3.Text
If x = "+" Then Text3.Text = a + b
Label1.Caption = a & x & b & "=" & Text3.Text '标签进行最终显示,防止输入错误
If x = "-" Then Text3.Text = a - b
Label1.Caption = a & x & b & "=" & Text3.Text
If x = "*" Then Text3.Text = a * b
Label1.Caption = a & x & b & "=" & Text3.Text
If x = "/" Then
   If b <> 0 Then Text3.Text = a / b Else: MsgBox "除数不能为零"
Label1.Caption = a & x & b & "=" & Text3.Text
End If
End Sub