2014-10-28 35 views
2

我使用Mathos Math parser來評估數學表達式。我試圖解析下面的表達式,但它拋出出現FormatException - 輸入字符串的不正確的格式..無法使用Mathos Math Prser評估數學表達式

Mathos.Parser.MathParser parser = new Mathos.Parser.MathParser(); 
string expression = "Math.pow((4),(5))"; //Or "Math.sqrt(1)"; 
string result = parser.Parse(expression).ToString(); 

在我的應用我使用MathDox MATHML編輯器,這給了我MATHML。使用這個mathml,我將它解析爲使用javascript的普通數學表達式,如給定here,然後將此表達式發送到我的c#代碼進行評估。 我的表情有什麼問題。

注:由於某些條件,我不評估JavaScript中的數學表達式。

+0

一個解決方案我喜歡是使用使用Microsoft JScript中的,而不是Mathos在C#中的javascript的eval。 http://odetocode.com/articles/80.aspx但它也在某些情況下失敗 – 2014-10-28 13:22:47

+0

你能否請檢查我的解決方案是否工作! – Artem 2014-11-30 17:54:11

回答

0

它不工作的原因是因爲pow函數被定義爲localFunction。下面的代碼應工作:

Mathos.Parser.MathParser parser = new Mathos.Parser.MathParser(); 
string expression = "pow(4,5)"; 
string result = parser.Parse(expression).ToString(); 

// or 

string expression2 = "4^5"; 
string result2 = parser.Parse(expression2).ToString(); 

Assert.AreEqual(result, result2); 

基本上,爲了使用Math.Pow功能,您既可以使用建立電運營商或內置電源功能的

您可以隨時更改電源功能的定義。這是當前defiinition:

  1. 冪函數:LocalFunctions.Add("pow", x => (decimal)Math.Pow((double)x[0], (double)x[1]));
  2. 電運營商:OperatorList.Add("^");OperatorAction.Add("^", (numberA, numberB) => (decimal)Math.Pow((double)numberA, (double)numberB));