Swift:双转换不一致。如何正确比较双打? [英] Swift: Double conversion inconsistency. How to correctly compare Doubles?

查看:62
本文介绍了Swift:双转换不一致。如何正确比较双打?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的功能,将温度从˚C转换为˚K。

I have a very simple function to convert temperature from ˚C TO ˚K.

func convertKelvinToCelsius(temp:Double) ->Double {
        return temp - 273.15
}

我有一个单元测试来驱动此功能。这是问题所在:

And I have a unit test to drive this function. This is where the problem is:

  func testKelvinToCelsius(){
            var check1 = conv.convertKelvinToCelsius(200.00) // -73.149999999999977
            var check2 = 200.00 - 273.15                     // -73.149999999999977
            var check3 = Double(-73.15)                      // -73.150000000000006

            //Passes
            XCTAssert(conv.convertKelvinToCelsius(200.00).description == Double(-73.15).description, "Shoud convert from celsius kelvin")

            //Fails
            XCTAssert(conv.convertKelvinToCelsius(200.00) == Double(-73.15), "Shoud convert from celsius kelvin")
     }

当你添加一个断点并检查check1,check2和check3的值,他们非常有趣:

When you add a breakpoint and check the values of check1, check2 and check3, they are very interesting:

check1  Double  -73.149999999999977
check2  Double  -73.149999999999977
check3  Double  -73.150000000000006

问题:


  1. 为什么Swift为check1 / check2和check3返回不同的值

  1. Why does Swift return different values for check1/check2 and check3

如何获得第二个测试通过,因为写作就像我做了一个测试一样的气味。为什么我必须将双打转换成字符串才能对比?

How can I get the second test to pass, because writing it like I did the test1 smells. Why should I have to convert Doubles to Strings to be able to compare them?

最后,当我 println check1,check2和check3,它们都打印为'-73.15'。为什么?为什么不准确打印,不要混淆程序员!

Finally, when I println check1, check2 and check3, they all print to be '-73.15'. Why? Why not print accurately, and not confuse the programmers!?

要复制:

只需在操场上输入 200 - 273.15 == -73.15 ,然后观看 false !!

Just type 200 - 273.15 == -73.15 in you playground and watch it go false!!

推荐答案

这是浮点值的预期行为。 它们不能100%准确地表示。

This is expected behavior for floating point values. They cannot be 100% accurately represented.

您可以使用 XCTAssertEqualWithAccuracy 函数来断言浮点值在彼此的给定范围内。

You can use the XCTAssertEqualWithAccuracy function to assert floating point values are within a given range of each other.

原因 println 打印所有的相同值是因为它内部将它们四舍五入为小数(我假设)。

The reason println prints the same value for all is because it internally rounds them to two decimals (I assume).

这篇关于Swift:双转换不一致。如何正确比较双打?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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