简体   繁体   English

通过乘以1.0或加1d将int转换为double?

[英]Converting an int to a double by multiplying by 1.0 or adding 1d?

As far as I know, to convert an integer to a double one can multiply the former by "1.0". 据我所知,将整数转换为双精度整数可以将前者乘以“ 1.0”。 It's apparently also possible to add "1d" (the double literal) to it. 显然也可以在其中添加“ 1d”(双字面量)。 What, then, is the difference? 那么,有什么区别呢?

Thanks! 谢谢!

So, if you mean "add the d to the end of the numeral"...then there's no difference. 因此,如果您的意思是“将d加到数字的末尾”……那么没有区别。 In Java, by default, all floating-point literals are double . 在Java中,默认情况下,所有浮点文字都是double

So these two literals are the same thing: 因此,这两个文字是同一回事:

41.32
41.32d

If you were to add f instead of d , then one would be a float instead of a double . 如果要添加f而不是d ,那么将是float而不是double

You can change an int to a double in this way, too: 您也可以通过这种方式将int更改为double

113
113d

If you're multiplying an int with a double to get a double , then the int is being promoted to a double so that the floating-point arithmetic can take place. 如果将int乘以double以得到double ,则该int 被提升为 double以便可以进行浮点运算。

From the JLS: 从JLS:

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules: 扩展原语转换(第5.1.2节)适用于转换以下规则指定的一个或两个操作数:

  • If either operand is of type double , the other is converted to double . 如果其中一个操作数的类型为double ,则另一个操作数将转换为double

  • Otherwise, if either operand is of type float , the other is converted to float . 否则,如果其中一个操作数的类型为float ,则另一个将转换为float

  • Otherwise, if either operand is of type long , the other is converted to long . 否则,如果其中一个操作数的类型为long ,则另一个将转换为long

  • Otherwise, both operands are converted to type int . 否则,两个操作数都将转换为int类型。

Adding 'd' is like an explicit cast to a double, multiplying will also convert to double cause 加'd'就像是对double的显式强制转换,相乘也将转换为double原因

If either operand is of type double, the other is converted to double before the operation is carried out. 如果一个操作数的类型为double,则在执行该操作之前将另一个转换为double。

and 1.0 is a double, so multiplying an int by 1.0 , would give a result of type double, but would also convert the other operand to double 和1.0是一个double值,因此将int乘以1.0会得到double类型的结果,但也会将另一个操作数转换为double

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM