gpt4 book ai didi

Java 故障?减数?

转载 作者:搜寻专家 更新时间:2023-10-31 08:15:42 25 4
gpt4 key购买 nike

这是 Java 中的一个小故障吗?

我去解决这个表达式:3.1 - 7.1

我得到答案:-3.9999999999999996

这是怎么回事?

最佳答案

可以在此处找到很好的解释。 http://www.ibm.com/developerworks/java/library/j-jtp0114/

Floating point arithmetic is rarely exact. While some numbers, such as 0.5, can be exactly represented as a binary (base 2) decimal (since 0.5 equals 2-1), other numbers, such as 0.1, cannot be. As a result, floating point operations may result in rounding errors, yielding a result that is close to -- but not equal to -- the result you might expect. For example, the simple calculation below results in 2.600000000000001, rather than 2.6:

double s=0;

for (int i=0; i<26; i++)
s += 0.1;
System.out.println(s);

Similarly, multiplying .1*26 yields a result different from that of adding .1 to itself 26 times. Rounding errors become even more serious when casting from floating point to integer, because casting to an integral type discards the non-integral portion, even for calculations that "look like" they should have integral values. For example, the following statements:

  double d = 29.0 * 0.01;
System.out.println(d);
System.out.println((int) (d * 100));

will produce as output:

 0.29
28

which is probably not what you might expect at first.

有关详细信息,请参阅提供的引用。

关于Java 故障?减数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8099468/

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