Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

objective c - XCode How to evaluate String formula with an X expression inside

I'm tring to evaluate a string formula to a float but, I cannot find a solution. Here is an example. I need to calculate about 200 formulas in this way.

- NSString *Formula;
- Float  *Result;
- Float *x

- x = 12;
- Formula = @"12.845*x+(-0.505940)";

Result = Evaluation / Calculation (Formula);

Then I'll use Result as a result from formula. --> Result = @"12.845*x+(-0.505940)";

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...