使用NSExpression计算值的平方?

时间:2012-10-24 08:03:29

标签: objective-c expression

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

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

3 个答案:

答案 0 :(得分:1)

将上面的代码替换为:

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

答案 1 :(得分:1)

NSNumber *number1 = [NSNumber numberWithInteger:2];        
NSNumber *number2 = [NSNumber numberWithInteger:4];

NSString *strSqr=[NSString stringWithFormat:@"%@%@%@",number1,@"+",number2];

NSExpression *arrayExpression = [NSExpression expressionForConstantValue: number1];

NSArray *arrNum=[NSArray arrayWithObjects:[NSExpression expressionWithFormat:strSqr],arrayExpression,nil];

NSExpression* expression =[NSExpression expressionForFunction:@"raise:toPower:" arguments:arrNum];

 NSLog(@"powerExp:%@",expression);

 int  resultSum = [[expression expressionValueWithObject:nil context: nil] intValue];
 NSLog(@"resultnum:%d",resultSum);`

我得到了输出:

 powerExp:(2 + 4) ** 2

 resultnum:36

答案 2 :(得分:1)

使用**而不是^

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

但要注意基金会的权力功能是左联想的(这是错误的)。见Dave Delong的帖子。

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