Question #2 Equation Solution

Equation Solution (#2)

Description:

Normally mathematicians use infix notation for equations, however there are other notations, such as prefix notation. An infix equation would look like ( 1 * 2 ) + 3 = 5, however prefix form would look like + * 1 2 3 = 5. An expression in prefix notation lists the operator first, followed by its two operands, which might also be expressions. Someone in the math department has asked you to write a simple program that will take an input file of prefix notation expressions, compute them, and convert them to infix form.

Problem Statement:

Write the above program.

Specifications:

The input file will consist multiple expressions, one equation per line ( though some lines may be blank). The only operators that you need to include in your program are +, -, *, /. The numbers in the equations will all be integers, but they might be proceeded by a -, indicating they are a negative number. One or more spaces and/or tabs will separate each operator and number. The calculations are to be done in floating point, but the output number should be rounded to the nearest integer ( round 1/of 2 and greater fractions to the next biggest absolute integer). The resulting infix notation should be properly parenthesized, but unnecessary parenthesis should not be added. If an equation is not in the correct form, then an error with the equation line should be output.

The input and output mentioned will come from, and be stored in the following filenames: prefix.in, and prefix.out (respectively).

Sample Input:

+ 1 2
* + 1 2 -3
****\3 -2 1
* + - -2 3 4 5
/ 3 + 4
1 * 2 / 4 + 2 1
/ -10 4

Sample Output:

1 + 2 = 3
( 1 + 2 ) * -3 = -9
Error in equation: "****\3 -2 1"
( ( -2 - 3 ) + 4 ) * 5 = 25
3 / ( 4 + 1 ) = 1
2 * ( 4 / ( 2 + 1 ) ) = 3
-10 / 4 = -3


Click to see a sample input
Click to see a sample output