算术表达式中的从字面int到Double强制 [英] Literal Int to Double coercion in arithmetic expressions

查看:130
本文介绍了算术表达式中的从字面int到Double强制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在评估表达式之前,Swift似乎对包含Double变量的表达式中的文字Int操作数应用了浮点传染(如在其他语言中所称).在某处是否有关于此的明确声明?我无法找到有关期望的具体描述.

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.

例如,假设我有let b = 0.14.然后,以下所有内容将产生相同的结果. (我正在使用Swift 5.0.1.)

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

那太好了,因为它似乎对操作顺序不敏感,因此似乎可以更容易地预测结果是什么. (我敢肯定,这种行为与某些其他语言不同.)但是,我无法找到任何有关将Int操作数与Double变量混合的情况的预期声明.我查看了以下页面,以期找到一些东西:表达式基本运算符

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?

推荐答案

Swift似乎会应用浮点传播

It appears that Swift applies floating point contagion

实际上不是.出现这种方式是因为Double符合 ExpressibleByIntegerLiteral ,这解释了为什么这是可能的:

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

let double: Double = 1

但不是:

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

这篇关于算术表达式中的从字面int到Double强制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆