我遇到了一个奇怪的问题,我想了解以下背景:
func printIntervals(_ colors: Int) {
let start = 0.4 - (Double(colors) - 1) / 10
print("start: \(start)")
for i in stride(from: start, through: 0.4, by: 0.1) { print ("i:\(i)")}
}
printIntervals(1)
printIntervals(2)
printIntervals(3)
printIntervals(4)
printIntervals(5)
printIntervals(6)
printIntervals(7)
printIntervals(8)
给我这个输出:
colors: 1 start: 0.4
i:0.4
colors: 2 start: 0.3
i:0.3
i:0.4
colors: 3 start: 0.2
i:0.2
i:0.3
i:0.4
colors: 4 start: 0.1
i:0.1
i:0.2
i:0.3
colors: 5 start: 0.0
i:0.0
i:0.1
i:0.2
i:0.3
i:0.4
colors: 6 start: -0.1
i:-0.1
i:2.77555756156289e-17
i:0.1
i:0.2
i:0.3
i:0.4
colors: 7 start: -0.2
i:-0.2
i:-0.1
i:5.55111512312578e-17
i:0.1
i:0.2
i:0.3
colors: 8 start: -0.3
i:-0.3
i:-0.2
i:-0.0999999999999999
i:1.11022302462516e-16
i:0.1
i:0.2
i:0.3
如您所见,某些函数调用将包含 0.4 值,而其他函数则不会...我的快速解决方法是将步幅改为 0.41,因此这绝对是一个精度问题。
但是如果之前的值打印为 0.3(不是 0.300001),为什么在增加 0.1 时会跳过 0.4?为什么它只在某些情况下发生 - 但始终如一?