开发者

What is the best way to execute math expression? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicates:

Is there a string math evaluator in .NET?

Best and shortest way to evaluate mathematical expressions

I have a string variable

string exp = "12+34+4*56+(23*45+12)2/30"

what is the best way of doing it ? without the using of third party 开发者_运维问答dll ?


You need a mathematical expression parser. The best way in my opinion is not reinventing the wheel. An existing open source solution NCalc is a good choice.


First translate it to an Expression Tree. If you use the built in Expression classes you get a compile method for free which gives you a compiled delegate, which thus is quite fast to evaluate. This is useful if you want to evaluate your expression for different parameters.


The classic way by Knuth is to first convert the Infix expression to a Postfix one and then evaluate the postfix expression, see link text. Both of these steps use a Stack to do most of the processing and are fairly easy to do.


Use IronPython:

ScriptEngine engine = PythonSingleton.Instance.ScriptEngine;
ScriptSource source =
engine.CreateScriptSourceFromString(code, SourceCodeKind.Expression);

Object res = source.Execute();

(Code copied from this article)


Add [, ] as operators inside start and end of your string then:

Read numbers fill them in stack and read operators and do same, when you rich the operator which its value is lower or equal to previous operator in stack POP previous operator and act on the available numbers in numbers stack: *:3, /:3, ):4, +:1,-:1

[12+34+4*56] ==>
Round 1: Numbers Stack: 12, Operator stack:[
Round 2: Numbers Stack: 12, Operator stack:[, +(1)
Round 3: Numbers Stack:12,34, Operator stack: [,+(1)
Round 4: Numbers Stack:12,34, Visited new operator with same or lower value (1) remove previous operator and pop 2 number from number stack and operate on them: So
Round 4: Numbers Stack:46, Operator stack: [,+(1)
Round 5: Numbers Stack:46,4 , Operator stack: [,+(1)
Round 6: Numbers Stack:46,4 , Operator stack: [,+(1),*(2)
Round 7: Numbers Stack:46,4,56, Operator stack: [,+(1),*(2)
Round 7: Numbers Stack:46,4,56, Operator stack: [,+(1),*(2) now operator item `]` want to be add, and it's priority is lower than all operators so operators sould be remove from stack and by each operator one number going to be removed:
Round 7: Numbers Stack:46,224 Operator stack: [,+(1),
Round 8: Numbers Stack:270 Operator stack: [,
Round 8: return 270, because ']' intered in  Operator stack


This is a bit of a hack, but I use javascript's eval function in .net through:

var myEngine = Microsoft.JScript.Vsa.VsaEngine.CreateEngine();
string result =  Microsoft.JScript.Eval.JScriptEvaluate(expression, myEngine).ToString();

As an added bonus you can mix in mathematical functions into your expression if needed

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜