【问题标题】:Unable to evaluate math expressions using Mathos Math Prser无法使用 Math Os 数学解析器计算数学表达式
【发布时间】:2014-12-23 10:52:10
【问题描述】:

我正在使用Mathos Math parser 来评估数学表达式。我正在尝试解析以下表达式,但它抛出 FormatException - 输入字符串格式不正确..

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,我使用给定here 的javascript 将它解析为普通的数学表达式,然后将此表达式发送到我的c# 代码进行评估。 我的表情有什么问题。

注意:由于某些情况,我不会在 javascript 中评估数学表达式。

【问题讨论】:

  • 我喜欢的一个解决方案是在 c# 中使用 javascript eval,使用 Microsoft Jscript 而不是 Mathos。 odetocode.com/articles/80.aspx 但在某些情况下它也会失败
  • 能否请您检查我的解决方案是否有效!

标签: javascript c# parsing math evaluation


【解决方案1】:

之所以不起作用是因为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 函数,您可以使用内置幂运算符或内置幂函数。

您可以随时更改幂函数的定义。这是当前的定义:

  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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-25
    • 2013-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多