数学表达式解析器 [英] Mathematical expressions parser

查看:107
本文介绍了数学表达式解析器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
.NET中是否有字符串数学计算器?

Possible Duplicate:
Is there a string math evaluator in .NET?

我需要实现数学表达式解析器.它必须计算以下表达式:

I need to implement mathematical expression parser. It has to evaluate the following expressions:

  • 基本运算符(+,-,*,/,%[模运算符])
  • 优先操作,例如2 *(4-1)
  • sin,cos,tan,cotan,log(base,number)函数
  • 允许使用诸如sin(cos(log(2,32)))之类的组合物
  • 电源操作,例如2 ^ 5

首先,我想使用JScript eval函数.但这并不是不安全的,没有电力运营商.中学我在Internet上搜索了一些图书馆.但事实证明,我无法使用它们.因此,问题如下:JScript eval函数调用的安全性如何?我的任务是否有任何标准的.net工具?如果不是,哪种算法最好?到目前为止,我正在尝试构建表达式树,然后对其进行编译以获取结果.

First that I wanted to use JScript eval function. But it's not unsafe and no power operator. Secondary I searched for some libraries in Internet. But as turned out, I cannot use them. So the question is the following: how safe is JScript eval function calling and are there any standard .net tools for my task? If not, which algorithm is the best? As of now I'm trying to build expression tree and then compile it to get result.

推荐答案

您可以尝试 NCalc

Dictionary<string, int> dict = new Dictionary<string, int>() {
    {"a",1} ,
    {"b",4}
};

NCalc.Expression exp = new NCalc.Expression("a + b / 2 * myfunc(3.14)");

exp.EvaluateFunction += (s, e) =>
    {
        var d = (double)e.Parameters[0].Evaluate();
        e.Result = Math.Cos(d);
    };

exp.EvaluateParameter += (s, e) =>
    {
        e.Result = dict[s];
    };

var result = exp.Evaluate();

这篇关于数学表达式解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆