Home > OS >  how to add together the values ​from the RPN algorithm
how to add together the values ​from the RPN algorithm

Time:01-19

I’m writing calculator that calculates values ​​from expressions:

3 (23/24)*34/24

I used RPN algorithm: https://en.wikipedia.org/wiki/Reverse_Polish_notation

I have now sorted expression in String:

3 23 24 / 34 * 24 /

I don't have any idea how can I get value from this expression.

Thx

CodePudding user response:

The basic idea behind RPN is that there is a stack that all the arguments get put on, then taken off for an operation.

For this set, the basic flow will be:

Element Stack a b
push 3 3
push 23 3,23
push 24 3,23,24
-divide
pop b 3,23 24
pop a 3 23 24
push a/b 3, 0.9583
end-divide
push 34 3, 0.9583, 34
-multiply
pop b 3, 0.9583 34
pop a 3 0.9583 34
push a*b 3, 32.5833
end-multiply
push 24 3, 32.5833, 24
-divide
pop b 3, 32.5833 24
pop a 3 32.5833 24
push a/b 3, 1.3576
end-divide
add
pop b 3 1.3576
pop a 3 1.3576
push a b 4.3576
end-add

pop solution!

CodePudding user response:

The basic algorithm is based on a stack-like structure

For each token in the expression:

  • if it is a number: push it
  • if it is a symbol: pop 2 values; do the matched operation; push the result

E.g.:

"3 23 24 / 34 * 24 /  "
                                             Stack
3:  push 3                                   |   3
23: push 23                                  |   3    23
24: push 24                                  |   3    23     24
/:  pop (24),   pop (23),    push 23/24      |   3     0.95
34: push 34                                  |   3     0.95  34
*:  pop (34),   pop (0.95),  push 0.95*34    |   3    32.58
24: push 24                                  |   3    32.58  24
/:  pop (24),   pop (32.58), push 32.58/24   |   3     1.35
 :  pop (1.35), pop (3),     push 3 1.35     |   4.35

The last value that remains in the stack is the result

  • Related