当前学习Swift,有很多方法可以找到不同种类的Integer的最大值和最小值,如Int.max和Int.min。
有没有办法找到Double和Float的最大值?此外,我应该提到哪种文件这种问题?我目前正在读苹果的Swift编程语言。
虽然没有Double.max,它在C float.h头中定义,你可以通过import Darwin在Swift中访问它。
- import Darwin
- let fmax = FLT_MAX
- let dmax = DBL_MAX
这些分别是大约3.4 * 10 ^ 38和1.79 * 10 ^ 308。
但要记住,浮点数并不简单(浮点数从来不是这么简单)。当保持数字这么大,你失去精度,以类似的方式丢失精度与非常小的数字,因此:
- let d = DBL_MAX
- let e = d - 1.0
- let diff = d - e
- diff == 0.0 // true
- let maxPlusOne = DBL_MAX + 1
- maxPlusOne == d // true
- let inf = DBL_MAX * 2
- // perhaps infinity is the “maximum”
- inf == Double.infinity // true