gpt4 book ai didi

java - Java 中的原始类型转换和赋值

转载 作者:行者123 更新时间:2023-11-30 09:02:18 27 4
gpt4 key购买 nike

为什么以下内容有效

float f = 10l // OK  32 bits to 64 ?

float 只有 32 位,long 是 64 位,所以 long 中没有 float 的空间

而这个没有

long l = 10f    //compile error 

有人可以向我解释一下类型转换的工作原理吗?

最佳答案

longfloat 的转换特别允许由JLS, Section 5.1.2 赋值。 :

19 specific conversions on primitive types are called the widening primitive conversions:

  • byte to short, int, long, float, or double

  • short to int, long, float, or double

  • char to int, long, float, or double

  • int to long, float, or double

  • long to float or double

  • float to double

A widening primitive conversion from int to float, or from long to float, or from long to double, may result in loss of precision - that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode (§4.2.4).

因此,值的范围被覆盖,但可能会损失精度。这是允许和预期的。

另一行:

long l = 10f;

是一个primitive narrowing conversion ,其中 JLS, Section 5.2 "Assignment Contexts" , 不特别允许:

Assignment contexts allow the use of one of the following:

  • an identity conversion (§5.1.1)

  • a widening primitive conversion (§5.1.2)

  • a widening reference conversion (§5.1.5)

  • a boxing conversion (§5.1.7) optionally followed by a widening reference conversion

  • an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.

请注意,显式转换将允许缩小原始转换。

long l = (long) 10f; // Compiles

关于java - Java 中的原始类型转换和赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26046571/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com