#K96142. Postfix Expression Evaluation
Postfix Expression Evaluation
Postfix Expression Evaluation
Given a string representing an expression in postfix notation (also known as reverse Polish notation), compute its value. The expression consists of numbers (which can be integers or decimals) and the operators +
, -
, *
, and /
. The operators and operands are separated by spaces. You are required to evaluate the expression from left to right using a stack-based method and output the result rounded to two decimal places.
For example, the expression 3 4 +
should evaluate to 7.00, and the expression 3 4 + 2 *
should evaluate to 14.00. The arithmetic operation for division is standard, and you may assume that the input is well-formed.
The evaluation process can be summarized as follows:
1. Read the expression from stdin as a single line.
2. Split the expression into tokens delimited by spaces.
3. Process each token: if it is a number, push it onto the stack; if it is an operator, pop the two topmost numbers from the stack, apply the operator, and push the result back onto the stack.
4. After processing all tokens, the number remaining on the stack is the final result (rounded to two decimal places) which is printed to stdout.
The arithmetic operators satisfy the usual properties, and the division operation is defined by the formula \(a / b\) where \(a\) and \(b\) are the two operands with \(b \neq 0\).
inputFormat
The input consists of a single line that contains the postfix expression. The tokens are separated by spaces. Each token is either a numeric value (possibly with decimals) or one of the operators: '+', '-', '*', or '/'.
outputFormat
Output the result of evaluating the expression, rounded to two decimal places. The result should be printed as a single line to stdout.
## sample3 4 +
7.00