Float divison and casting in Swift

可紊 提交于 2019-12-04 23:46:09

First, you should use Double and not Float. Float gives you very limited precision. Why you would want 6 digits precision with Float when you could have 15 digits with Double is hard to understand.

Second, a compiler does exactly what you tell it.

Float (sum) / Float (numbers.count)

takes the integer "sum", takes the integer "numbers.count", converts both to Float and divides. Divison of Float gives a result in this case of 3.5.

Float (sum/numbers.count)

divides the integer "sum" by the integer "numbers.count". Division of integers gives an integer result, which is the integer quotient disregarding any remainder. 21 / 6 equals 3 with a remainder of 3. So the result of the division is 3, which you then convert to the Float 3.0.

return Float(sum/numbers.count) 

In this statement, sum and numbers.count are both Ints, so they use an Int division function which returns an Int. Since an Ints only have whole values, this result loses any decimal precision. A Float is then created from this Int and it has decimal digits, but the precision has already been lost at this point.

return Float(sum)/Float(numbers.count)

In this statement, Floats are made out of sum and numbers.count, then divided. Because they are Floats this time, a division function for Floats is used which returns a Float. In this statement the precision is never lost, so it returns a more accurate result.

You can also just add a .0 on to the end of any integer and do:

let red = CGFloat(226.0/255.0)

red will be CGFloat 0.88627450980392152

I use this method to covert RGB Photoshop colors:

NSColor.init(calibratedRed: red, green: green, blue: blue, alpha: 1.0)

At least this works well in this case but I would think in other uses also.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!