#C13018. Evaluate Mathematical Expressions
Evaluate Mathematical Expressions
Evaluate Mathematical Expressions
You are given a list of mathematical expressions as strings. Your task is to evaluate each expression and print the result. The expression may contain the binary operators \(+\), \(-\), \(*)\) and \(/\). If an expression is invalid (due to division by zero, syntax errors or unknown variables), print "Error" for that expression.
For example, the expression "2 + 3" evaluates to \(5\), and "10 / 4" evaluates to \(2.5\). Note that if the evaluation returns a float (for division), you must print the result as is (e.g., 5.0 or 2.5) while arithmetic operations with only integers should yield integer results.
Input Format: The first line contains an integer \(T\) representing the number of expressions. The following \(T\) lines each contain a single expression.
Output Format: For each expression, print the evaluated result on a new line. If an expression is invalid, print "Error".
inputFormat
The input is read from stdin
and has the following format:
T expression_1 expression_2 ... expression_T
Where:
T
is an integer representing the number of expressions.- Each
expression_i
is a string containing a mathematical expression.
outputFormat
Output to stdout
the evaluation result of each expression in the order given. Each result should be printed on a new line. If an expression evaluates successfully, print its numerical result (as an integer or float). If the expression is invalid (e.g., division by zero, syntax error, or use of unknown variables), print "Error".
3
2 + 3
5 * 6
10 - 2
5
30
8
</p>