将数学方程的NSString转换为值 [英] Convert NSString of a math equation to a value

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

问题描述

我想知道如何评估方程式的字符串表达式,就好像它是一个真正的方程式:

I would like to know how to evaluate a string representation of an equation as if it were a real equation:

if(@"15+14==23")
{
    //True statement...
}
else
{
    //False statement....
}



我想返回false,因为15 + 14不等于23.我如何让这个工作?

I want to return "false" because 15+14 does not equal 23. How can I get this to work?

推荐答案

这里是一个例子如何做到 NSPredicate

Here is an example how to do it with NSPredicate:

NSPredicate *p = [NSPredicate predicateWithFormat:@"1+2==3"];
NSLog(@"%d", [p evaluateWithObject:nil]);
p = [NSPredicate predicateWithFormat:@"1+2==4"];
NSLog(@"%d", [p evaluateWithObject:nil]);

第一个 NSLog 产生 1 ,因为 1 + 2 == 3 第二个产生 0

The first NSLog produces 1 because 1+2==3 is true; the second produces 0.

这篇关于将数学方程的NSString转换为值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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