#C14973. Evaluate Mathematical Expression
Evaluate Mathematical Expression
Evaluate Mathematical Expression
You are given a string representing a mathematical expression that may include non‐negative numbers (integer or decimal), the binary operators +
, -
, *
, and /
, as well as parentheses ( )
which denote explicit grouping. Your task is to evaluate the expression and output its numerical result as a float.
The evaluation must respect the standard operator precedence rules and correctly handle nested parentheses. If the expression is malformed (for example, if it contains mismatched parentheses or an incomplete operator expression), you must output an error message starting with "Invalid expression:" followed by a description of the error.
Note: All divisions are floating point divisions. The input is provided via standard input (stdin) and your program should output the result to standard output (stdout).
inputFormat
The input consists of a single line containing a string expression that represents the mathematical expression. The expression may contain spaces.
Example: 3 + 5 * (2 - 8) / 2
outputFormat
Output a single line containing the evaluated result as a float if the expression is valid. If the expression is invalid, output an error message in the format:
Invalid expression: [error description]## sample
2 + 3
5.0