且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

数学表达式解析:当 + 后跟 - 时输出不正确

更新时间:2023-09-13 10:37:04

提升到乘法和乘法都很好.在这一点上,我们被简化为 36-21+15.在这里我们必须记住,我们正在添加 -21.所以我们需要回到 -7 .当我建立我的数字列表(它处理一位以上的数字)时,我会在它前面的数字上加上减号.

All is well with raising to a power and multiplication. At that point we are simplified to 36-21+15. Here we must remember that we are adding -21. So we need to go back to -7 . When I build my list of numbers (it handles numbers of more than one digit) I add the minus sign to the number it precedes.

此代码不处理十进制数或括号.如果您愿意,我认为您可以添加除法运算符.

This code does not handle decimal numbers or parenthesis. I think you will be able to add the division operator, if you wish.

Private NumList As New List(Of Double)
Private OperatorList As New List(Of String)

Private Sub OpCode()
    Dim Input = "14*3^2-7*3+15*3"
    PopulateLists(Input)
    Dim OpIndex As Integer
    Dim NewNum As Double
    Dim operators = {"^", "*", "+"} 'Note: no minus sign, the minus goes with the number
    For Each op In operators
        Do
            OpIndex = OperatorList.IndexOf(op)
            If OpIndex = -1 Then
                Exit Do
            End If
            Select Case op
                Case "^"
                    NewNum = NumList(OpIndex) ^ NumList(OpIndex + 1)
                Case "*"
                    NewNum = NumList(OpIndex) * NumList(OpIndex + 1)
                Case "+"
                    NewNum = NumList(OpIndex) + NumList(OpIndex + 1)
            End Select
            NumList.RemoveAt(OpIndex + 1)
            NumList(OpIndex) = NewNum
            OperatorList.RemoveAt(OpIndex)
        Loop
    Next
    MessageBox.Show(NumList(0).ToString) 'Displays 150
End Sub

Private Sub PopulateLists(Input As String)
    Dim strNum As String = ""
    For Each c As Char In Input 'Be careful here, the IDE wants to add () at the end of this line - it doesn't belong
        If Char.IsDigit(c) Then
            strNum &= c
        ElseIf c = "-" Then
            OperatorList.Add("+") 'We are adding a negative number
            NumList.Add(CDbl(strNum)) 'Add the last number we accumulated so we can start a new one with the minus sign
            strNum = "-" 'Start a new number with the minus sign
        Else 'The other operators are added to the list
            OperatorList.Add(c)
            NumList.Add(CDbl(strNum))
            strNum = ""
        End If
    Next
    NumList.Add(CInt(strNum)) 'The last number which will not be followed by an operator
End Sub