Literal Int to Double coercion in arithmetic expressions [duplicate]

筅森魡賤 提交于 2020-02-06 09:03:25

问题


It appears that Swift applies floating point contagion (as it is called in other languages) to literal Int operands in an expression containing a Double variable before evaluating the expression. Is there an explicit statement about that somewhere? I wasn't able to find a specific description about what to expect.

For example, suppose I have let b = 0.14. Then the following all yield the same result. (I am working with Swift 5.0.1.)

 19> 5.0 * b / 6.0
$R12: Double = 0.11666666666666668
 20> 5 * b / 6
$R13: Double = 0.11666666666666668
 21> 5 / 6 * b
$R14: Double = 0.11666666666666668
 22> b * 5 / 6
$R15: Double = 0.11666666666666668
 23> (5 / 6) * b
$R16: Double = 0.11666666666666668
 24> b * (5 / 6)
$R17: Double = 0.11666666666666668

That's great, it seems to make it easier to predict what the result will be, since it appears to be insensitive to the order of operations. (Incidentally that behavior differs from some other languages, I'm pretty sure.) However, I wasn't able to find any explicit statement about what should be expected in the case of literal Int operands mixed with a Double variable; I looked at these pages in hope of finding something: Expressions, Basic Operators, Advanced Operators. Can anyone point to a spec which describes what to expect in such cases?


回答1:


It appears that Swift applies floating point contagion

It doesn't, actually. It appears that way, because Double conforms to ExpressibleByIntegerLiteral, which explains why this is possible:

let double: Double = 1

but not:

let i: Int = 1
print(i * 1.23) // error: binary operator '*' cannot be applied to operands of type 'Int' and 'Double'


来源:https://stackoverflow.com/questions/58718509/literal-int-to-double-coercion-in-arithmetic-expressions

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