1
我想創建一個數字從1.0到1.25的幾個數組。我使用下面的代碼:經過數字迭代0.01增加.0000000000000001幾次迭代後
heightDisplayArray: [String] = []
heightArray: [Double] = []
for i in 1.stride(to: 1.25, by: 0.01){
heightDisplayArray.append("\(i) meters")
heightArray.append(i)
}
print (heightDisplayArray)
print (heightArray)
出於某種原因,結果被追加爲預期heightDisplayArray,但增加了一些意想不到的號碼heightArray。控制檯顯示以下內容:
["1.0 meters", "1.01 meters", "1.02 meters", "1.03 meters", "1.04 meters", "1.05 meters", "1.06 meters", "1.07 meters", "1.08 meters", "1.09 meters", "1.1 meters", "1.11 meters", "1.12 meters", "1.13 meters", "1.14 meters", "1.15 meters", "1.16 meters", "1.17 meters", "1.18 meters", "1.19 meters", "1.2 meters", "1.21 meters", "1.22 meters", "1.23 meters", "1.24 meters"]
[1.0, 1.01, 1.02, 1.03, 1.04, 1.05, 1.0600000000000001, 1.0700000000000001, 1.0800000000000001, 1.0900000000000001, 1.1000000000000001, 1.1100000000000001, 1.1200000000000001, 1.1300000000000001, 1.1400000000000001, 1.1500000000000001, 1.1600000000000001, 1.1700000000000002, 1.1800000000000002, 1.1900000000000002, 1.2000000000000002, 1.2100000000000002, 1.2200000000000002, 1.2300000000000002, 1.2400000000000002]
如何糾正此問題?我可以將heightArray更改爲字符串數組而不是雙精度值,但我更願意找到實際導致這種情況發生的原因。
http://stackoverflow.com/questions/588004/is-floating-point-math-broken – Mat