将具有数学表达式的字符串转换为float [英] Convert a string with mathematical expressions into a float

查看:175
本文介绍了将具有数学表达式的字符串转换为float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文本字段包含数学表达式: 12 + 45-6 是否可以将此字符串转换为数字?

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/>

我也发现这 https://github.com/unixpickle/ANExpressionParser

推荐答案

't依赖外部库是首先将字符串转换为一个标记序列,然后使用分流算法链接到简单的堆栈机器上。

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.

这篇关于将具有数学表达式的字符串转换为float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆