浮动divison和铸造在Swift [英] Float divison and casting in Swift
问题描述
我试图学习Swift,我做了一个简单的平均函数:
func average 。) - > Float {
var sum = 0
数字中的数字{
sum + = number
}
return Float(sum)/ Float(numbers.count)
}
average(1,2,3,4,5,6)
这给了我正确的结果:3.5
然而,我想知道为什么我必须把两个sum和numbers.count转换为浮点数。我试过这样做:
return Float(sum / numbers.count)
但它只给我3.0
解决方案,你应该使用Double而不是Float。浮动给你非常有限的精度。为什么你想要6位数字精度与浮点,当你可以有15位数字与双是很难理解。
其次,编译器完全按照你的说法。
Float(sum)/ Float(numbers.count)
取整数sum,取整数numbers.count,将两者转换为Float和divides。浮点除法得到的结果在这种情况下为3.5。
Float(sum / numbers.count)
将整数sum除以整数numbers.count。整数除法得到一个整数结果,这是整数商,不考虑任何余数。 21/6等于3,余数为3.所以除法的结果是3,然后你转换为Float 3.0。
I'm trying to learn Swift and I made a simple average function:
func average(numbers: Int...) -> Float { var sum = 0 for number in numbers { sum += number } return Float(sum)/Float(numbers.count) } average(1,2,3,4,5,6)
This gives me the correct result: 3.5 However, I am wondering why I have to cast both sum and numbers.count to floats. I tried casting this way:
return Float(sum/numbers.count)
but it gives me just 3.0
解决方案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.
这篇关于浮动divison和铸造在Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!