我正在尝试创建一个可以解析表达式的程序,比如3x^3 + 7x^2 + 6x - 9。我正在使用一个递归系统来做这件事。目前,我只是在测试是否通过在表达式中使用常量来获得我输入的表达式的正确输出。这段代码适用于大多数表达式,但是当我有一个减号后跟一个正号时,两个项都会被减去(第一项应该减去,第二项应该加上)。输入4*3^2-7*3+5*3就是一个这样的例子。这个问题的答案是30,但是程序执行4*3^2-7*3-5*3并输出0。我不确定如何解决这个问题。
代码:
Private Function ParseExpr(ByRef expression As String)
Dim op, op1 As Integer
op = ParseFactor(expression)
If expression.Length <> 0 Then
If (expression(0) = "+") Then
expression = expression.Substring(1, expression.Length - 1)
op1 = ParseExpr(expression)
op += op1
ElseIf (expression(0) = "-") Then
expression = expression.Substring(1, expression.Length - 1)
op1 = ParseExpr(expression)
op -= op1
End If
End If
Return op
End Function发布于 2021-01-20 10:15:44
升幂和乘法一切都很好。此时,我们被简化为36 -21 +15。在这里,我们必须记住我们添加的是-21。所以我们需要回到-7。当我构建我的数字列表(它处理超过一位数的数字)时,我将减号加到它前面的数字上。
此代码不处理十进制数字或括号。如果您愿意,我认为您可以添加除法运算符。
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 Subhttps://stackoverflow.com/questions/65798782
复制相似问题