"expressionValueWithObject"方法可以将数字解释为浮点数而不是整数吗? [英] Can 'expressionValueWithObject' method interpret numbers as floats instead of integers?

查看:150
本文介绍了"expressionValueWithObject"方法可以将数字解释为浮点数而不是整数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个计算器,它将输入记录在名为"inputLabel"的标签中,然后在另一个名为"outputLabel"的标签中输出答案(类似于图形计算器).当用户完成输入表达式后,该表达式被存储在一个NSString对象中,然后用NSPredicate类进行解析并用NSExpression类进行评估.我的工作原理是,但是我注意到对于某些特定的操作,答案是不正确的.例如,如果用户键入"25/2 计算器返回12,这显然是不正确的.但是,如果用户键入"25/2.0"或"25.0/2",则计算器将返回12.5,这正是我想要的.似乎NSExpression方法'expressionValueWithObject'正在解释如果是这种情况,是否可以更改"expressionValueWithObject"方法以将操作数解释为浮点数?

I am making a calculator that logs input in a label named "inputLabel' and then outputs the answer in a different label named "outputLabel" (similar to a graphing calculator). Once the user is finished entering the expression, the expression is stored in an NSString object and then parsed with the NSPredicate class and evaluated with the NSExpression class. What I have works, but I have noticed for particular operations the answers are not correct. For example, if the user types in "25/2" the calculator returns 12, which is obviously incorrect. However, if the user types in "25/2.0" or "25.0/2" the calculator returns 12.5 which is what I want. It seems that the NSExpression method 'expressionValueWithObject' is interpreting the operands as integers instead of floats. If this is the case, is there a way that I change the 'expressionValueWithObject'method to interpret the operands as floats?

Brain.m

-(float)performCalculation: (NSString *)operation
{
    NSPredicate *parsed = [NSPredicate predicateWithFormat:[operation stringByAppendingString:@"=1.0"]];
    NSExpression *inputExpressionParsed = [(NSComparisonPredicate *)parsed leftExpression];
    NSNumber *result = [inputExpressionParsed expressionValueWithObject:inputExpressionParsed context:nil];

    return [result floatValue];
}

ViewController.m

ViewController.m

- (IBAction)equalsPressed:(id)sender
{
    //self.inputLabel.text = [self.inputLabel.text stringByAppendingString:@".0"];
    NSString *inputExpression = self.inputLabel.text;
    self.inputLabel.text = [self.inputLabel.text stringByAppendingString:@"="];
    float result = [self.brain performCalculation:inputExpression];
    self.outputLabel.text = [NSString stringWithFormat:@"%g", result];
}

推荐答案

否,NSExpression无法做到这一点.您可以尝试将".0"附加到所有整数 在对字符串进行评估之前,但是更好的解决方案可能是使用适当的" 例如,数学表达式解析器 https://github.com/davedelong/DDMathParser

No, NSExpression cannot do that. You could try to append ".0" to all integer numbers in the string before evaluating it, but the better solution is probably to use a "proper" math expression parser, for example https://github.com/davedelong/DDMathParser

这篇关于"expressionValueWithObject"方法可以将数字解释为浮点数而不是整数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆