Expression assessment

I run an expression evaluation program like. My problem is that I cannot figure out how to handle operation priorities. I used recursion to find the innermost pair of parentheses and, when I found, resolve the expression inside them, for example:

Evaluate("2 + (3 * 5)")

will repeat the call this way:

Evaluate("3 * 5")

now, since there are no brackets, it calculates the result and calls itself at another time:

Evaluate("2 + 15")

Well, the return value is 17, as expected. But if I call Evaluate("2 + 3 * 5"), the result will be as follows:

Evaluate("2 + 3 * 5")
Evaluate("5 * 5")

.
. , ? , .
, , ?

+3
4

, . , + *, * aaaa * bbbb aaaa * bbbb. , +.

(, ^), , .

0

, , , Antlr .net.

http://www.codeproject.com/KB/recipes/sota_expression_evaluator.aspx

, , , , , .

, , . .

. '+' '*'

additiveExpression: multiplicativeExpression '+' multiplicativeExpression
multiplicativeExpression: number '*' number

.

Antlr, , , , - , .

- , , Antlr, - , . , .

+2

-, , : http://en.wikipedia.org/wiki/Polish_notation#Computer_programming. .

, . infix .

, . "2 + 3 * 5":

2 + 3 * 5
b = 3 * 5
    -convert b-
b = * 3 5
2 + b
    -convert expression-
+ 2 b
    -expand b-
+ 2 * 3 5

, . , . , , , .

, . :

- . :

  • ,
  • ()
  • ( ), .
  • №3 .

, , , . , / . , , ..

, :)

+2

. , +, . , , .

2 + 3 * 5 2 + (3 * 5).

+1
source

Source: https://habr.com/ru/post/1785782/


All Articles