Reputation: 2058
Not exactly sure what it would be called?
But anyway, I am wondering how exactly one would make a calculator where the user types his equation into a text box, and then when the user hits "=" it calculates everything the user has typed in.
ex. user types: 1 + 1 * (1 +2) hits enter 6 (is displayed)
-EDIT- I screwed up on my math :P 4 (is displayed)
I couldn't find any articles talking about this on the internet, for I didn't really know what to search for. So if anyone could help, or at least point me in the right direction. It would be greatly appreciated.
Thanks, Regards.
Upvotes: 0
Views: 441
Reputation: 25740
These are called math parsers.
There are two very good libraries that are freely available: DDMathParser and GCMathParser.
See this question for more details.
They are much more capable than NSExpression.
Upvotes: 3
Reputation: 8944
1 + 1 * (1 +2) hits enter 6 (is displayed)
hmm, i'm sure there're lot of samples of human math, but 1 + 1x(1+2) != 6 :)
One recommendation from me would be to collect all unrecognized character-groups and consider it to be variables, then let a user to enter the values. Like 1 + y*(1+z), enter, y=1, z=2, enter, result=4.
Upvotes: 1
Reputation: 55573
What you are looking for is something with NSExpression
I think:
NSExpression *expression = [NSExpression expressionWithFormat:inputText, nil];
NSNumber *result = [expression expressionValueWithObject:nil context:nil];
I have tested NSExpression with mathematical symbols (0-9
, +
, -
, *
, /
, (
, )
) and it seems to work as expected. Give it a shot, it may just work for you.
Upvotes: 2
Reputation: 26375
You might try looking up "infix notation" and "parse trees" as a start.
Upvotes: 1