Reputation: 21
I'm using NSExpression
to evaluate a formula in a string.
Example -
NSString *formula = @"7+11";
NSExpression *exp = [NSExpression expressionWithFormat: formula];
NSNumber *expResult = [exp expressionValueWithObject:nil context:nil];
Everything works just fine but...
What if I have the following formula "7+x=18"? How can I evaluate this formula and find "x" and get the result 11?
Upvotes: 2
Views: 1641
Reputation: 12503
NSString *formula = @"12.845*x+(-0.505940)";
float x = 12.0;
NSExpression *expr = [NSExpression expressionWithFormat:formula];
NSDictionary *object = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:x], @"x", nil];
float result = [[expr expressionValueWithObject:object context:nil] floatValue];
NSLog(@"%f", result);
// Output: 153.634064
Original Answer here
Upvotes: 4