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

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

4

3 回答 3

2

使用 ** 代替 ^

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

但要注意 Foundation 的幂函数是关联的(这是错误的)。见戴夫德隆的帖子。

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

于 2013-01-14T23:35:25.797 回答
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);
于 2012-10-24T08:17:59.160 回答
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
于 2012-10-26T12:50:55.833 回答