28
6
You must write a program that evaluates a string that would be entered into an advanced calculator.
The program must accept input using stdin and output the correct answer. For languages that do no have functions to accept stdin, you may assume the functions readLine
and print
to handle these tasks.
Requirements:
- Does not use any kind of "eval" functions
- Can handle floating point and negative numbers
- Supports at least the +, -, *, /, and ^ operators
- Supports brackets and parenthesis for overriding the normal order
- Can handle input containing one or more spaces between the operators and numbers
- Evaluates the input using the standard order of operations
Test Cases
Input
10 - 3 + 2
Output
9
Input
8 + 6 / 3 - 7 + -5 / 2.5
Output
1
Input
4 + [ ( -3 + 5 ) * 3.5 ] ^ 2 - 12
Output
41
1Is it ok if the outputted numbers have a trailing
.0
at the end if they're integers? Also: how accurate does the calculator have to be (regarding floating point precision and such)? – sepp2k – 2011-02-06T18:45:38.4671The output can have a trailing
.0
on the end. I'm not too sure about the precision, but more is better. – Kevin Brown – 2011-02-06T20:33:37.5901
The Stack Overflow version was Mathematical expression evaluator (full PEMDAS). Though many of the answer to that one are counting lines (?!?). Still there are several compact answers in c.
– dmckee --- ex-moderator kitten – 2011-02-06T21:30:51.417Bonus for PN/RPN calculators? – Mateen Ulhaq – 2011-03-20T04:49:22.513