问题
I would like to know how to evaluate a string representation of an equation as if it were a real equation:
if(@"15+14==23")
{
//True statement...
}
else
{
//False statement....
}
I want to return "false" because 15+14 does not equal 23. How can I get this to work?
回答1:
Here is an example how to do it with NSPredicate
:
NSPredicate *p = [NSPredicate predicateWithFormat:@"1+2==3"];
NSLog(@"%d", [p evaluateWithObject:nil]);
p = [NSPredicate predicateWithFormat:@"1+2==4"];
NSLog(@"%d", [p evaluateWithObject:nil]);
The first NSLog
produces 1
because 1+2==3
is true; the second produces 0
.
回答2:
So, this is a problem that I believe is a lot more complicated than the linked question lets on (although the question is asking for a "simple" equation parser).
Fortunately for you, I think this is a really interesting problem and have already written one for you: DDMathParser.
It has a good amount of documentation, including things like how to add it to your project and a high overview of its capabilities. It supports all of the standard mathematical operators, including logical and comparison operators (||
, &&
, ==
, !=
, <=
, etc).
In your case, you'd do something like this:
NSNumber *result = [@"15+14 == 23" numberByEvaluatingString];
if ([result boolValue] == YES) {
....True statement....
} else {
.....False statement.....
}
As a heads up, DDMathParser
is made available under the MIT license, which requires you to include the copyright information and the full text of the license in anything that uses it.
回答3:
NSString *equation = @"15+14==29";
NSPredicate *pred = [NSPredicate predicateWithFormat:equation];
NSExpression *LeftExp = [pred leftExpression];
NSExpression *RightExp = [pred rightExpression];
NSNumber *left = [LeftExp expressionValueWithObject:nil context:nil];
NSNumber *right = [RightExp expressionValueWithObject:nil context:nil];
if ([left isEqualToNumber:right]) {
NSLog(@"yes left is equal to right");
}
else{
NSLog(@"yes left is NOT equal to right");
}
NSLog(@"left %@", left);
NSLog(@"right %@", right);
来源:https://stackoverflow.com/questions/8618005/convert-nsstring-of-a-math-equation-to-a-value