我已经实现了一个自定义计算器,我使用以下代码来计算类似5 + 3 * 5-3的算术表达式。
- (NSNumber *)evaluateArithmeticStringExpression:(NSString *)expression {
NSNumber *calculatedResult = nil;
@try {
NSPredicate * parsed = [NSPredicate predicateWithFormat:[expression stringByAppendingString:@" = 0"]];
NSExpression * left = [(NSComparisonPredicate *)parsed leftExpression];
calculatedResult = [left expressionValueWithObject:nil context:nil];
}
@catch (NSException *exception) {
NSLog(@"Input is not an expression...!");
}
@finally {
return calculatedResult;
}
}
但是当我使用除法运算的整数时,结果只得到整数。让我们说5/2我结果是2。由于整数除法,它适合于编程的动摇。
但我需要浮点结果。
我怎样才能获得它而不是扫描表达式字符串并将整数除数替换为浮点数。在我们的示例5 / 2.0或5.0 / 2中。
答案 0 :(得分:8)
我自己找到了。
- (NSNumber *)evaluateArithmeticStringExpression:(NSString *)expression {
NSNumber *calculatedResult = nil;
@try {
NSPredicate * parsed = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"1.0 * %@ = 0", expression]];
NSExpression * left = [(NSComparisonPredicate *)parsed leftExpression];
calculatedResult = [left expressionValueWithObject:nil context:nil];
}
@catch (NSException *exception) {
NSLog(@"Input is not an expression...!");
}
@finally {
return calculatedResult;
}
}
它只是用操作数" 1.0 *"开始表达式。一切都将是浮点计算。
NSPredicate * parsed = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"1.0 * %@ = 0", expression]];
NB:谢谢@Martin R但是,我的问题不是关于整数除法,它完全是关于NSExpression的。我的最后一句话明显被排除在外。
@Zaph,这里使用异常处理有很多原因。这是我的方法接受用户输入的地方,用户可以输入类似w * g和 - expressionValueWithObject:context:将抛出异常,我必须避免我的应用程序的异常终止。如果用户输入了有效的表达式,那么他/她将以NSNumber的形式获得答案,否则将获得nil NSNumber对象。