使用NSExpression计算值的平方? [英] Calculate square of value using NSExpression?

查看:172
本文介绍了使用NSExpression计算值的平方?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

NSString *formul=@"3^2";
NSExpression *e = [NSExpression expressionWithFormat:formul];
int result = [[e expressionValueWithObject:nil context:nil] intValue];
NSLog(@"formule:%d", result);

我正在尝试计算(a + b)^ 2。

I am trying to calculate (a+b)^2.

推荐答案

使用**代替^

NSString *formul=@"3 ** 2";
NSExpression *e = [NSExpression expressionWithFormat:formul];
int result = [[e expressionValueWithObject:nil context:nil] intValue];
NSLog(@"formule:%d", result);

但要注意基金会的权力函数是关联的(这是错误的)。见Dave Delong的帖子。

But beware Foundation's power function is left associative (which is wrong). See Dave Delong's post.

http://funwithobjc.tumblr.com/post/6196535272/parsing-mathematical-expressions

这篇关于使用NSExpression计算值的平方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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