gpt4 book ai didi

objective-c - 使用 NSExpression 查找指数值?

转载 作者:行者123 更新时间:2023-11-29 13:26:26 26 4
gpt4 key购买 nike

我正在尝试使用 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]: unrecognized selector sent to instance 0x7439e60 2012-10-22 16:04:04.034 operator[3958:c07] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI doubleValue]: unrecognized selector sent to instance 0x7439e60'

最佳答案

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

关于objective-c - 使用 NSExpression 查找指数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13011119/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com