#C13118. Evaluate Arithmetic Expression
Evaluate Arithmetic Expression
Evaluate Arithmetic Expression
You are given a string representing a mathematical expression containing non-negative integers, parentheses, and the binary operators +
, -
, *
, and /
. The expression may include spaces. Your task is to parse and evaluate the expression by respecting the operator precedence (i.e. following the PEMDAS/BODMAS rules). In addition, you must handle error cases: if the expression is empty, contains an invalid character, or attempts to perform division by zero, output the corresponding error message.
Note that if the expression contains the division operator /
, the result should be printed as a floating point number with one decimal place (even if the fractional part is 0). Otherwise, if the result is an integer, it should be printed without a trailing decimal part.
Examples:
3 + 2
outputs5
8 / 2
outputs4.0
(1 + 3) * (2 + 4)
outputs24
3 / 0
outputsdivision by zero
3 + a
outputsError: Invalid character in expression
(empty input) outputs
Error: Invalid expression
inputFormat
The input consists of a single line which is a valid mathematical expression (or an invalid one in error cases). All spaces should be ignored.
outputFormat
Output the evaluated result of the expression. If the expression involves division, print the result as a float with one decimal place. If any error occurs, such as division by zero, an invalid character, or an empty expression, output an appropriate error message.
## sample3 + 2
5