gpt4 book ai didi

java - 关于浮点型精度

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:06:18 26 4
gpt4 key购买 nike

我不明白这是为什么

float f = Integer.MAX_VALUE;
System.out.println(Integer.MAX_VALUE);
System.out.println((int)f);

产生相同的行,

以及为什么会这样

Float f2 = (float) Integer.MAX_VALUE;
System.out.println(Integer.MAX_VALUE);
System.out.println(f2.intValue());

我的意思是, float 的尾数长度是 2^23-1。它如何设法保持整数的 max_value,即 2^31 - 1

最佳答案

How does it manage to keep max_value of integer, which is 2^31 - 1?

其实不然。 f 的值为 2147483648

然而,narrowing primitive conversionfloatint 限制值。它到达了这一部分:

  • Otherwise, one of the following two cases must be true:

    • The value must be too small (a negative value of large magnitude or negative infinity), and the result of the first step is the smallest representable value of type int or long.

    • The value must be too large (a positive value of large magnitude or positive infinity), and the result of the first step is the largest representable value of type int or long.

您可以通过将数字更大来轻松地看到这一点:

float f = Integer.MAX_VALUE;
f = f * 1000;
System.out.println(Integer.MAX_VALUE); // 2147483647
System.out.println((int)f); // 2147483647

或者通过转换为 long 来代替,这显然不需要在同一点进行限制:

float f = Integer.MAX_VALUE;
System.out.println(Integer.MAX_VALUE); // 2147483647
System.out.println((long)f); // 2147483648

关于java - 关于浮点型精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16557999/

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