I've written this relatively commonplace algorithm that parses a given input and then converts it from infix to postfix.

The problem that I'm having deals with the order of events. It's possible that I'm misunderstanding something about postfix operations...

Let's say I want to calculate 10/(2-4)/5 : The answer should be -1, however, the answer I get is -25.

10,2,4,-,5,/,/

Why? Because my 'postfix' goes and does the -2/5 first, then divides 10/-.4, which is clearly wrong:

Is there something simple I'm missing?

有帮助吗?

解决方案

Your expression has two division operations at the same level (no parentheses). Assuming that division associates left-to-right, then the expression should be interpreted as

(10 / (2 - 4)) / 5

This should then turn into the following in postfix notation:

10 2 4 - / 5 /

The postfix you ended up with would correspond to the ordering:

10 / ((2 - 4) / 5)

Generating the reverse Polish from a parse tree should clear up the problem, assuming the parse tree is generated correctly from the infix expression.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top