D
D
DyudinDaniil2020-11-04 18:25:05
C++ / C#
DyudinDaniil, 2020-11-04 18:25:05

How to implement a calculator with brackets in C (via reverse Polish notation)?

It is required to implement a calculator with brackets in SI (via reverse Polish notation)
Example:
Expression:
1+2+3
Reverse Polish Notation:
1 2 + 3 +
Result:
6

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2020-11-04
@wataru

The sorting yard algorithm . You can switch to the English version of the wiki, there is a detailed example, and pseudocode.
If something more independent is required of you, then do this - find the operation with the lowest priority in the line (the one that will be performed last). Recursively output the reverse polish notation for the left and right half, then output/do the operation.
To find the operation - go through the line, counting how many parentheses are currently open. Remember the position of the rightmost encountered "+"/"-" and "*"/"/". If nothing is found, then you can bite off the outer pair of brackets (if there are no brackets, then the whole line is a number). Otherwise, if there is + or - - this is the very last operation. If there is none, then it will be * or / - take it.
This works for a square, unlike the algorithm by reference, but it is written in an elementary way.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question