如何阻止 NSExpression 四舍五入 [英] How to stop NSExpression from rounding

查看:27
本文介绍了如何阻止 NSExpression 四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在用 Swift 3 制作计算器,但遇到了一些问题.

我一直在使用 NSExpression 来计算用户方程,但答案总是四舍五入.

为了检查答案是否四舍五入,我计算了 3/2.

let expression = NSExpression(format: "3/2");让答案:Double = expression.expressionValue(with: nil, context: nil) as!双倍的;Swift.print(String(答案));

以上代码输出1.0,而不是1.5.

有谁知道如何阻止 NSExpression 四舍五入?谢谢.

解决方案

该表达式使用整数除法,因为您的操作数是整数.试试这个:

let expression = NSExpression(format: "3.0/2.0");让答案:Double = expression.expressionValue(with: nil, context: nil) as!双倍的;Swift.print(String(答案));

考虑以下代码:

let answer = Double(3/2)

answer 在这种情况下仍然是 1.0 因为 3/2 在插入之前被评估为 1Double 初始值设定项中.

然而,这段代码会给answer 1.5 的值:

let answer = Double(3.0/2.0)

这是因为 3.0/2.0 将根据 Double 的除法运算而不是 Integer 的除法运算进行评估.>

I've been making a calculator in Swift 3, but have run into some problems.

I have been using NSExpression to calculate the users equation, but the answer is always rounded.

To check that the answer was rounded, I calculated 3 / 2.

let expression = NSExpression(format: "3 / 2");
let answer: Double = expression.expressionValue(with: nil, context: nil) as! Double;
Swift.print(String(answer));

The above code outputs 1.0, instead of 1.5.

Does anyone know how to stop NSExpression from rounding? Thanks.

解决方案

The expression is using integer division since your operands are integers. Try this instead:

let expression = NSExpression(format: "3.0 / 2.0");
let answer: Double = expression.expressionValue(with: nil, context: nil) as! Double;
Swift.print(String(answer));

Consider the following code:

let answer = Double(3 / 2)

answer in this case would still be 1.0 since 3 / 2 is evaluated to 1 before being inserted in the Double initializer.

However, this code would give answer the value of 1.5:

let answer = Double(3.0 / 2.0)

This is because 3.0 / 2.0 will be evaluated based on the division operation for Double instead of the division operation of Integer.

这篇关于如何阻止 NSExpression 四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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