2014-11-06 23 views
2
Dim equation As String 
Dim numbers() As String 
Dim operators As New List(Of String) 
Dim result As Double 
Dim rx As New Regex("(\+|\-|\*)+") 
Dim matches As MatchCollection 

equation = TextBox1.Text 
numbers = equation.Split(New String() {"+"c, "-"c, "*"c}, StringSplitOptions.None) 
matches = rx.Matches(equation) 

Dim m1 As Match 

For Each m1 In matches 
    operators.Add(m1.Value) 
Next 

result = CInt(numbers(0)) 
Dim i As Integer 

For i = 1 To numbers.GetUpperBound(0) 
    Select Case operators(i - 1) 
     Case "*" 
      result *= CDec(numbers(i)) 
     Case "+" 
      result += CDec(numbers(i)) 
     Case "-" 
      result -= CDec(numbers(i)) 
     Case " ^" 
      result ^= CDec(numbers(i)) 
    End Select 
Next 
MessageBox.Show(result) 

這是我的代碼,例如「1 + 4 + 2 * 3」我如何編輯我的代碼,先乘以先乘,然後除+和 - 。有人有想法嗎?我如何設置運營商的優先級在vb.net

+1

使用括號 - '(2 * 3)+ 1 + 4'。請注意,您必須找出最佳使用偏差的位置,以免影響結果,但'('和')'具有更高的優先權。 [Visual Basic中的運算符優先級](http://msdn.microsoft.com/en-us/library/fw84t893.aspx) – Tim 2014-11-06 09:21:52

+0

我該如何將它們添加到我的代碼中並從它們開始? – gew 2014-11-06 09:27:16

回答

0

我加入mXparser數學解析庫,這是寫在C#,但符合CLS - 它可以用VB很容易地使用。請按照mXparser Hello World tutorial for VB

Dim e As Expression = New Expression("2+(3-sin(pi))") 
mXparser.consolePrintln(e.calculate()) 

問候