#C14202. Basic Calculator Simulation
Basic Calculator Simulation
Basic Calculator Simulation
You are required to implement a basic calculator that evaluates a given mathematical expression represented as a string. The expression can include non-negative numbers and the operators +, -, *, and / along with parentheses. The evaluation must obey the standard order of operations, i.e. the precedence rules: addition and subtraction have lower precedence than multiplication and division. In mathematical notation, you should consider:
$$+,- \quad \text{(lowest precedence)}$$
$$*,/ \quad \text{(higher precedence)}$$
Your task is to parse and evaluate the expression without using built-in evaluation functions such as eval()
. The calculator must also handle error cases: if division by zero occurs, the program should output:
ZeroDivisionError: Division by zero is not allowed.
If the expression is malformed or contains invalid characters (e.g. letters), the program should output:
ValueError: Invalid mathematical expression.
The input will be provided via standard input (stdin) as a single line containing the mathematical expression. The output should be printed on standard output (stdout) as a floating point number with one decimal place, or as an error message if an error occurs.
inputFormat
The input consists of a single line containing a string expression
which represents a mathematical formula. The expression may include numbers, the operators +
, -
, *
, /
, and parentheses ( )
.
outputFormat
If the expression is valid and no errors occur, output the evaluated result as a floating point number with exactly one decimal place. If a division by zero occurs, output the exact message:
ZeroDivisionError: Division by zero is not allowed.
For any other invalid expression, output:
ValueError: Invalid mathematical expression.
3+2
5.0