Calculate square of value using NSExpression?

匆匆过客 提交于 2019-12-24 01:39:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!