问题
NSString *formul=@"3^2";
NSExpression *e = [NSExpression expressionWithFormat:formul];
int result = [[e expressionValueWithObject:nil context:nil] intValue];
NSLog(@"formule:%d", result);
I am trying to calculate (a+b)^2.
回答1:
Use ** instead of ^
NSString *formul=@"3 ** 2";
NSExpression *e = [NSExpression expressionWithFormat:formul];
int result = [[e expressionValueWithObject:nil context:nil] intValue];
NSLog(@"formule:%d", result);
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
回答2:
Replace the code above with:
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);
回答3:
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);`
I've got the output:
powerExp:(2 + 4) ** 2
resultnum:36
来源:https://stackoverflow.com/questions/13045089/calculate-square-of-value-using-nsexpression