2012-11-01 61 views
7

我想使用VB計算一個字符串的算術表達式,任何想法?從一個字符串使用VB評估數學表達式

舉個例子:「X + 2」從一個文本框,我想計算表達式

+1

我想你的意思是你想執行它作爲一個*算術*表達。一個* regular *表達式[完全不同](http://en.wikipedia.org/wiki/Regular_expression)。我相信你知道已經 – MarkJ

+3

可能重複[在JavaScript中做像Eval的vb.net中的數學](http://stackoverflow.com/questions/1452282/doing-math-in-vb-net-like-eval- in-javascript) – Boann

回答

9

可以使用NCalc這一點。它也接受參數,如X,Y,Z,...

Dim e As Expression = new Expression("2 + 3 * 5") 
Msgbox(17 = e.Evaluate()) 
+0

你知道它是否可以解析[LaTex](http://en.wikipedia.org/wiki/LaTeX)? –

+0

@JohanLarsson對不起,我不知道:( –

+0

在.Net框架上沒有bultin解決方案? –

1

您可以通過點擊添加的Microsoft Visual參考按鈕使用mxparser庫這個purpose.Give參考在您的項目mxparser.dll Studio.mxparser庫源代碼或最新的dll文件可以從www.mathparser.org.mXparser是Java,Android,C#.NET(CLS)庫的數學解析器。

Imports org.mariuszgromada.math.mxparser 
Private Function evaluate(ByVal str As String) AS Double 
Dim expr As Expression = New Expression(str) 
DIM d1 As Double 
d1=0 
d1=expr.calculate() 
return d1 
End Function 

調用函數可以如下。

DIM str as String 
str="" 
str=((45^5)/45))*(5*6) 

Dim d as Double 
d=0 
d=evaluate(str) 
MsgBox(" The result of the expression is " + d.ToString) 
+0

對於mXparser(http://mathparser.org/)即使是很好的「hello world」教程VB :-) http://mathparser.org/mxparser-hello-world/mxparser-hello-world-visual-basic/ –

6
Dim equation As String = "2+6/2" 
Dim result = New DataTable().Compute(equation, Nothing) 
+0

這個答案不需要額外的庫來添加到項目:) – craigster