Postfix Polish C++entry

The expression (-a)-(-b) is given. Organize the calculation of this expression using the postfix Polish notation algorithm.

  • What will this entry look like in the stack?
    -- b 0 - a 0 (read from right to left)

  • Does char or int fit on the stack?

  • And how to make calculations?
Author: A K, 2016-04-13

2 answers

How to store in a stack - in this case, there are two stacks. One is for calculations, the other stores the Polish record itself (although it is no longer a stack, but just a queue).

The stack for calculations is best done of the int or double(float) type.

It is better to write the calculation itself in a regular string vector (although it can also be done in the stack, as it is convenient). And store in "normal order" (i.e., expand). That is, I would store such a {"0", "a", "-', "0", "b", "-", "-"}.

How to perform. The code in the loop reads the element with vector and looks at it. If it is a number (the first character is a digit) - puts it on the calculation stack, if it is a variable (a or b in your case, that is, the first character is a..z A..Z) - takes their value (for example, asks the user) and puts it on the stack. If there is an operation in the queue, it extracts two numbers from the stack, performs the operation, and puts the calculation result on the stack. At the end of the work, the top of the stack is simply printed out.

The actual code, I think you can write by yourself.

 1
Author: KoVadim, 2016-04-13 09:56:17

What will this entry look like in the stack? -- b 0 - a 0 (read from right to left)

No. This entry is not on the stack. A record is an input sequence of commands. And it is always written from left to right!

Does char or int fit on the stack?

When do you calculate the purchase price in a store, add up the prices of goods or their names? If you always add numbers in your life, where did the idea of putting symbols on the stack come from?

And how to make calculations?

Execute the input sequence of commands sequentially!

Here it is: 0 a - 0 b - -

  1. We put 0{[27] on the stack]}
  2. We put the value of the number a
  3. We take the last two numbers from the stack and subtract them, and put the result back on the stack
  4. We do the same with the commands 0 b -, the stack now contains numbers (-a) and (-b)
  5. Repeat the subtraction operation again, now the stack contains only one number is the result of the expression
  6. We take it out of the stack and show it to the user (or do something else, depending on what is required)
 1
Author: Pavel Mayorov, 2016-04-13 10:04:12