NSString *formul=@"3^2";
NSExpression *e = [NSExpression expressionWithFormat:formul];
int result = [[e expressionValueWithObject:nil context:nil] intValue];
NSLog(@"formule:%d", result);
我正在尝试计算 (a+b)^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。
使用 ** 代替 ^
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
将上面的代码替换为:
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);
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