Java 故障?减数?

标签 java double subtraction

这是 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/

相关文章:

java - 使用注释配置时在 Spring 3 中实现 HTTP Basic auth 弹出窗口的最简单方法

Java 将 double 更改为 Date

MySQL分页无需双重查询?

mysql - 通过MYSQL查询减去值

java - 无法在Java中使用正则表达式进行匹配

java - 如何使用 JAVA 在 MATLAB 中进行显式多线程处理?

java - SpringBoot 测试模块不在正确的类路径中搜索 log4j2 配置

C - 双模整数的下限

algorithm - 计算机对两个大数进行乘法、除法、减法、加法是否比较小的数花费更多的时间

r - 如何从R中的另一个向量中减去具有重复字符的完整字符向量