Create a stack calculator. A stack-oriented calculator (one that uses reverse Polish notation, allows the user to perform mathematical operations, but unlike the common in-fix notation (such as $3.2 + 5.7$), stack-oriented calculators have the user enter the operands first, and then the operator.
You will start with an empty array with some pre-determined capacity.
If the user enters a number, that number is put into the next available entry in the array. If the user enters an operator, the last two numbers are taken out of the array, the operation is performed on these two numbers, and the result is placed in place of the first. When an operation is performed, the result is displayed to the screen.
3.5 7.9 1.8 + -> 9.7 * -> 33.95
This is the approach a number of HP calculators use, and it has a clear advantage over traditional calculators: it is never necessary to use brackets, as the order of operations is not ambiguous.
To review the ambiguity of infix notation, the expression $3 + 5 \times 7$ could be interpreted as $(3 + 5) \times 7 = 8 \times 7 = 56$ or $3 + (5 \times 7) = 3 + 35 = 38$. By convention, we assume multiplication is performed first.
If we were using our stack-oriented calculator, these two operations would be
3 5 + -> 8 7 * -> 56
and
5 7 * -> 35 3 + -> 38
You may approach this project in one of three ways:
If you get an operator such as -, / and ^, there is a question of whether or not you meant to, for example, subtract the last entry added to the array from the second-last, or vice versa. We will use the convention that if you enter two numbers and then a non-commutative operator, you expected to perform them in order:
5 7 - -> -2 4 ^ -> 16 5 / -> 3.2
You can continue with this project as follows:
5 ! -> 120 sin 0.5806111842123142892824 2 ^ 0.3371093472324260 120 cos 0.8141809705265618 2 ^ 0.6628906527675741 + -> 120
Instead of only looking for numeric values versus operators, you could also allow the user to enter symbols representing specific values:
Symbol | Value |
---|---|
pi | 3.141592653589793 |
e | 2.718281828459045 |
phi | 1.618033988749895 |
gamma | 0.5772156649015329 |
inf | floating-point infinity |
nan | not-a-number |
If any of these constants are added, the result is placed on the stack.
If the user enters clear, reset the array and thereby emptying it.
+ Invalid operation: no entries in the array 5 7 + -> 12 clear 4 + Invalid operation: only one entry in the array