1

我正在尝试使用NSExpression如下方式计算指数值:

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

NSArray *arrNum=[NSArray arrayWithObjects:number1,number2,nil];
NSExpression *arrayExpression = [NSExpression expressionForConstantValue: arrNum];

NSArray *arrExp=[NSArray arrayWithObject:arrayExpression]; 

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

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

int  resultSum = [[expression expressionValueWithObject:nil context: nil] intValue];

NSLog(@"resultnum:%f",resultSum);

我得到了错误:

-[__NSArrayI doubleValue]:无法识别的选择器发送到实例 0x7439e60 2012-10-22 16:04:04.034 operator[3958:c07] *由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:'-[__NSArrayI doubleValue]:无法识别的选择器发送到实例 0x7439e60'

4

2 回答 2

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

NSExpression *expr1 = [NSExpression expressionForConstantValue:number1];
NSExpression *expr2 = [NSExpression expressionForConstantValue:number2];

NSArray *exprArgs = [NSArray arrayWithObjects:expr1, expr2, nil];

NSExpression *expression = [NSExpression expressionForFunction:@"raise:toPower:" arguments:exprArgs];
NSLog(@"powerExp:%@",expression);

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

输出:

powerExp:2 ** 4
resultnum:16
于 2012-10-24T10:41:57.197 回答
0

expressionForConstantValue:需要一个NSNumber. 你通过了NSArrayNSNumber

exp:函数采用单个数字 (n) 并返回 e^n。那是你想要做的吗?或者你的意思是使用raise:toPower:,它需要两个值?

于 2012-10-22T12:15:12.973 回答