Visual Basic - 计算器II编码困境

时间:2014-02-07 15:41:25

标签: vb.net visual-studio-2010

这是我在计算机科学I [Visual Basic 2010]

中发布的作业

目标: 如果尝试除以0,则修改CalculatorII案例研究以显示“ERROR”。 “如果为单个数字输入多个小数点,也应显示错误。

当我除以零或添加更多小数点时,我无法显示ERROR消息。这就是我在编码中所拥有的:

Public Class Form1
Dim operand1 As Double = 0
Dim operand2 As Double = 0
Dim op As String = Nothing
Dim newOperand As Boolean = True

Private Sub Number_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles _
    btnDot.Click, btn0.Click, btn1.Click, btn2.Click, btn3.Click, btn4.Click, btn5.Click, _
    btn6.Click, btn7.Click, btn8.Click, btn9.Click
    Dim btnNumberClicked As Button = sender
    If newOperand Then
        Me.txtDisplay.Text = btnNumberClicked.Tag
        newOperand = False
    Else
        Me.txtDisplay.Text &= btnNumberClicked.Tag
    End If


End Sub


Private Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
    Handles btnClear.Click
    Me.txtDisplay.Text = "0"
    operand1 = 0
    operand2 = 0
    newOperand = True
    op = Nothing
End Sub

Private Sub btnOff_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles _
    btnOff.Click
    Application.Exit()
End Sub


Private Sub btnOperator_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
    Handles btnPlus.Click, btnMinus.Click, btnTimes.Click, btnDivide.Click, btnEqual.Click, btnIntDivide.Click
    Dim operatorSelected As Button = sender

    If (operand1 = 0 And op = Nothing) Or op = "=" Then
        operand1 = Val(Me.txtDisplay.Text)
    ElseIf (operand1 = 0 And op = "/") Then
        MessageBox.Show("ERROR")
    Else
        operand2 = Val(Me.txtDisplay.Text)
        operand1 = Calculate(operand1, operand2, op)
        Me.txtDisplay.Text = operand1
    End If

    op = operatorSelected.Tag
    newOperand = True
End Sub


Function Calculate(ByVal firstOperand As Double, ByVal secondOperand As Double, _
                   ByVal op As String) As Double
    Select Case op
        Case "+"
            Return (firstOperand + secondOperand)
        Case "-"
            Return (firstOperand - secondOperand)
        Case "X"
            Return (firstOperand * secondOperand)
        Case "/"
            Return (firstOperand / secondOperand)
        Case "\"
    End Select
End Function

结束课程enter code here

1 个答案:

答案 0 :(得分:1)

操作数2必须是错误字段,您只需检查第一个操作数是否为0

变化 “ElseIf (operand1 = 0 And op = "/") ThenElseIf (operand2 = 0 And op = "/") Then

试一试:)