刚学VB,经过几天的努力,终于成功编写了一个计算器程序(不支持四则运算)
初步试用,还没发现问题,希望高手调试找找BUG,谢谢
源代码如下
Dim FirNum As Double, SecNum As Double, NewNumSign As Boolean, LastOp As Boolean, Op As String
'NewNumSign 新数标记 LastOp记录上次输入是否运算符(实现中途运算符的切换) Op 记录运算符
Private Sub ComCE_Click() '清空归零(本次输入)
Text1.Text = "0"
End Sub
Private Sub ComClear_Click() '置零,回归初始状态
form_load
End Sub
Private Sub ComDel_Click() '删除字符
Text1.Text = Left(Text1.Text, Len(Text1.Text) - 1)
LastOp = True
End Sub
Private Sub ComEqual_Click(Index As Integer) '计算
If LastOp = True Then
JiSuan '调用计算函数
LastOp = False
End If
Select Case ComEqual(Index).Caption
Case "+"
Op = "+"
Case "-"
Op = "-"
Case "*"
Op = "*"
Case "/"
Op = "/"
Case "="
Op = "="
End Select
NewNumSign = True
If Text1.Text <> "Error" Then
Text1.Text = SecNum
End If
End Sub
Private Sub ComNum_Click(Index As Integer) '数据输入
If NewNumSign = True Then
Text1.Text = ComNum(Index).Caption: NewNumSign = False
ElseIf Text1.Text = "0" Then
Text1.Text = ComNum(Index).Caption
Else: Text1.Text = Text1.Text & ComNum(Index).Caption
End If
NewNumSign = False
LastOp = True
End Sub
Private Sub ComPoint_Click() '小数点输入
If NewNumSign = True Then
Text1.Text = ".": NewNumSign = False
ElseIf InStr(Text1.Text, ".") Then
Exit Sub
Else: Text1.Text = Text1.Text & "."
End If
NewNumSign = False
LastOp = True
End Sub
Private Sub ComZF_Click() '正负的转换
If Text1.Text = "0" Then
Exit Sub
ElseIf InStr(Text1.Text, "-") Then
Text1.Text = Right(Text1.Text, Len(Text1.Text) - 1)
Else: Text1.Text = "-" & Text1.Text
End If
LastOp = True
End Sub
Private Sub form_load()
FirNum = 0: SecNum = 0: NewNumSign = True: LastOp = True: Op = ""
Text1.Text = "0"
Text1.FontSize = 12
End Sub
Private Sub Text1_Change() '显示合理化检查(本人认为此类程序的最好的解决方法)
If Text1.Text = "" Then
Text1.Text = "0"
ElseIf Left(Text1.Text, 1) = "." Then
Text1.Text = "0" & Text1.Text
ElseIf Left(Text1.Text, 2) = "-." Then
Text1.Text = "-0" & Right(Text1.Text, Len(Text1.Text) - 1)
End If
End Sub
Private Sub JiSuan() '计算函数
FirNum = Val(Text1.Text)
Select Case Op
Case "+"
SecNum = SecNum + FirNum
Case "-"
SecNum = SecNum - FirNum
Case "*"
SecNum = SecNum * FirNum
Case "/"
If FirNum = 0 Then
form_load
Text1.Text = "Error"
Exit Sub
Else: SecNum = SecNum / FirNum
End If
Case Else
SecNum = FirNum
End Select
End Sub