Infix to postfix for negative numbers
Asked Answered
U

1

6

How do I convert negative numbers from infix to postfix ?

Suppose I have a expression

a = - b - (-c-d)

In some places I read that you can parathesize the negative numbers like

a = (-b) - (-c-d)

But here if I do that, I will get a term like "ab-" at the beginning of the postfix expression which means a-b and is incorrect.

How do I convert this ?

Unfasten answered 21/10, 2017 at 7:56 Comment(5)
Why is this tagged c?Malisamalison
What postfix notation are you using?Malisamalison
I assume you are storing the values of the variables. Try storing the numbers as negative but show the operation in the character array as positive (+)Secluded
Does (-c-d) mean ((-c) - d) in which case I do not understand the question or does it mean (-c x d), in which case this question has no business being tagged [C] and is a maths question rather then a programming question.Shuntwound
"if I do that, I will get a term like "ab-..." eh!? Where the the a come from?Shuntwound
G
18

In infix notation, you must distinguish between the binary subtraction operator sub and the unary negation operator neg. Both are represented by a minus sign, but the context tells you which is which.

You've got a negation, when the minus as at the beginning of the expression, or after an opening parenthesis or after a binary operator:

    − (x + y)   →   x y add neg
    4 × − x   →   4 x neg mult
    2 × (− x + y)   →   2 x neg y add mult

You've got a subtraction when the minus is after a closing parenthesis or after a symbol, i.e. after a variable or number:

    1 − x   →   1 x sub
    (4 ∗ x) − 1   →   4 x mult 1 sub

Take care that the unary operator neg just takes one argument off the stack. If you want to stick with binary operators, you can push a zero before the second operand and use binary sub:

    − (x + y)   →   0 x y add sub
    4 x neg mult   →  4 0 x sub mult
    2 x neg y add mult   →   2 0 x sub y add mult

Finally, you can apply a similar logic to unary plus, which you can just ignore:

    + x   →   x
    + (x + y)   →   x y add

Georgiegeorgina answered 21/10, 2017 at 8:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.