数学表达式解析器

编程入门 行业动态 更新时间:2024-10-19 02:17:57
本文介绍了数学表达式解析器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复: .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函数调用的安全性如何?我的任务是否有任何标准的工具?如果不是,哪种算法最好?到目前为止,我正在尝试构建表达式树,然后对其进行编译以获取结果.

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

更多推荐

数学表达式解析器

本文发布于:2023-11-10 16:13:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575852.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   数学

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!