Convert a string with mathematical expressions into a float

跟風遠走 提交于 2019-12-01 13:12:34

问题


A text field contains mathematical expressions like: 12+45-6 Is possible to convert this string to a number?

Can we use the predicate facility?

NSString *foo = @"((a*b)/c+(d/5))+15";
// dummy predicate that contains our expression
NSPredicate *pred = [NSPredicate predicateWithFormat:[foo stringByAppendingString:@" == 42"]];
NSExpression *exp = [pred leftExpression];
NSNumber *result = [exp expressionValueWithObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:4], @"a",[NSNumber numberWithInt:7], @"b",[NSNumber numberWithInt:2], @"c",[NSNumber numberWithInt:20], @"d",nil]context:nil];
NSLog(@"%@", result); // logs "33"<br/>

I also found this https://github.com/unixpickle/ANExpressionParser


回答1:


One solution that doesn't rely on external libraries is to first convert the string into a sequence of tokens, then evaluate the expression using the shunting-yard algorithm chained onto a simple stack machine.




回答2:


You need to parse this input using a parser then evaluate it. I have heard of people having success using muParser for this, to save you writing it all yourself. Check it out. http://muparser.sourceforge.net/




回答3:


Yes. Read up on "expression evaluation", or use a ready-made script interpreter. JavaScript is available to all iOS programs as a part of WebView.




回答4:


Yes, of course it's possible.

You should look into infix to postfix conversion using a stack: http://scriptasylum.com/tutorials/infix_postfix/algorithms/infix-postfix/index.htm

And then look into how to evaluate a postix expression, also using a stack: http://scriptasylum.com/tutorials/infix_postfix/algorithms/postfix-evaluation/index.htm



来源:https://stackoverflow.com/questions/6809927/convert-a-string-with-mathematical-expressions-into-a-float

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!