visual basic从文本框中的表达式获取总和

时间:2015-03-05 14:41:03

标签: vb.net textbox

我正在VB 2010中开发一个计算器,用户点击该按钮,文本框应该包含单击的文本框的值。我希望如果单击“Enter”按钮,它应该显示文本框中表达式的结果。我尝试使用这些代码,但它无法正常工作。 (假设表达式框中可能包含“9 + 7 - 5”)

ResultBox.text=ExpressionBox.text

ResultBox.text=val(ExpressionBox.text)

我得到了在ExpressionBox中编写的字符串。我怎样才能得到这些结果?

1 个答案:

答案 0 :(得分:0)

这是一个基本样本。

适用于+, - ,*和/.

从左到右进行评估。

您还可以自己发展

我把它放在keyDown事件上,以便评估用户点击输入时的时间

Function evaluate(val1 As Double, val2 As Double, opr As String) As Double
    Dim result As Double = 0
    Select Case opr
        Case "+"
            result = val1 + val2
        Case "-"
            result = val1 - val2
        Case "*"
            result = val1 * val2
        Case "/"
            result = val1 / val2
    End Select
    Return result
End Function

Function evaluate(expression As String) As String
    Dim prevVal As String = ""
    Dim result As Double = 0
    Dim isStart As Boolean = True
    Dim prevExpression As String = ""
    For i As Integer = 0 To expression.Length - 1
        Dim curChar As String = expression.Substring(i, 1)
        Select Case curChar
            Case "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "."
                prevVal += curChar
            Case "+", "-", "*", "/"
                prevExpression = curChar
                If isStart Then
                    isStart = False
                    result = Val(prevVal)
                    prevVal = ""
                Else
                    result = evaluate(result, Val(prevVal), prevExpression)
                    prevVal = ""
                End If
        End Select
    Next
    result = evaluate(result, Val(prevVal), prevExpression)
    Return result.ToString()
End Function

Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
    If e.KeyCode = Keys.Enter Then
        TextBox1.Text = evaluate(TextBox1.Text)
    End If
End Sub