评估一个数学表达式 [英] Evaluating a mathematical expression

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

问题描述



首先我导入了图书馆

 使用System.Linq.Expressions; 

然后在我的代码中,

 表达式e = new Expression((450 * 5)+((3.14 * 7)/ 50)* 100); 
double result = e.Evaluate();

但是我收到错误为
无法创建抽象类或接口的实例' System.Linq.Expressions.Expression'



为什么上述不起作用?



如何评估这个?

解决方案

我去了Ncalc。
我正在为未来的用户发布我的代码,他们将像我一样遇到问题。



1.下载Ncalc(Binaries) http://ncalc.codeplex.com/releases/view/73656


  1. 在您的解决方案中引用dll(右键单击>添加参考>浏览> NCalc.dll)

  2. p>

    使用NCalc;


3.可以用作

  public Double Calculate(string argExpression)
{
//获取用户传递的字符串
string ExpressionToEvaluate = argExpression;
//在评估对象声明中传递字符串。
表达式z = new Expression(ExpressionToEvaluate);
//命令来评估**************字符串表达式的值
var result = z.Evaluate();
Double results = Convert.ToDouble(result.ToString());

返回结果;

}


Guys I am up with evaluating a string mathematical expression.

First I imported the library

using System.Linq.Expressions;

Then in my codes I did,

Expression e = new Expression("(450*5)+((3.14*7)/50)*100");
  double result = e.Evaluate();

however I get the error as Cannot create an instance of the abstract class or interface 'System.Linq.Expressions.Expression'

Why the above is not working?

How can I evaluate this ?

解决方案

I went for Ncalc. I am posting my codes for future users who will be on same problems like me.

1.Download the Ncalc(Binaries)http://ncalc.codeplex.com/releases/view/73656

  1. Reference the dll in your solution.(Right click > add reference > Browse > NCalc.dll)
  2. In codes

    Using NCalc;

3.May be used as

public Double Calculate(string argExpression)
        {
            //get the user passed string
            string ExpressionToEvaluate = argExpression;
            //pass string in the evaluation object declaration.
            Expression z = new Expression(ExpressionToEvaluate);
            //command to evaluate the value of the **************string expression
            var result = z.Evaluate();
            Double results = Convert.ToDouble(result.ToString());

            return results;

        }

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

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