You can use NSExpression
:
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
This works even with some functions such as sqrt
, exp
, ... See the NSExpression
documentation for a list of supported function.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…