试一试这个程序:public class Hello {
    public static void main(String[] args) {
        System.out.println("1.2 * 1.5 = " + 1.2 *1.5);
    }
}应该输出 1.2 * 1.5 = 1.80 吧!
可是输出竟是 1.2 * 1.5 = 1.799999999999999 !!
这是为什么?

解决方案 »

  1.   

    hehe ~ ^_^
    习惯了就好
      

  2.   

    这并不是JAVA的错,你可以在《Effictive Java》中看到“double, float类型不适合做科学计算”的建议,因为java缔造者在设计二者当初,目的是为了更快的计算,因此舍弃了精度。具体的原因我也不是很清楚。可以参考《深入JAVA虚拟机》中“数值计算”章节和《Effictive Java》相关条目。
      

  3.   


    由于原生对象保存数值的精度问题,出现这样的情况是很正常的(不管你用什么语言)。因此在java中需要使用BigDecimal 来进行精确计算,
    代码如下:    java.math.BigDecimal b1=new  java.math.BigDecimal(1.2);
        java.math.BigDecimal b2=new  java.math.BigDecimal(1.5);
        System.out.println(b1.multiply(b2,new MathContext(10) ));
      

  4.   

    Java是对的,你也是对的。:)良马固然好,但并不是每匹良马都会100%听从你的使唤,当然你不能因为某一匹马不听你的使唤你就断定它是错的或者坏的,对吧?所以应该选择适合你的马。btw,pigo和PoemCode解释得很详细。
      

  5.   

    1.79<9循环>绝对等于1.80;
    好比
     .
    0.9 = 1;并不是约等于;是绝对等于.可以证明的.
      

  6.   

    1.79<9循环>绝对等于1.80;
    好比
     .
    0.9 = 1;并不是约等于;是绝对等于.可以证明的.
    是的,这两个数字是一样的 1.79...9循环  = 1.80
      

  7.   

    to: pigo(少壮且行英雄梦,迟暮归守温柔乡) 
    用c就没有这个问题!
      

  8.   

    以前用java时也遇到过这种问题,不过还是无法解决
      

  9.   

    在java中,float和double类型的数都是用浮点码表示的,如果了解浮点的编码规则,那么可以知道浮点码不能精确的表示绝大多数的小数,它只能精确的表示 1/2,1/4这样的小数,因此它在表示其他的小数时只能近似的表示它们。
      

  10.   

    建议你看一下  JAVA核心技术(上) 这本书for example:Floating-point numbers are not suitable for financial calculation in which roundoff errors cannot be tolerated. For example, the command System.out.println(2.0 - 1.1) prints 0.8999999999999999, not 0.9 as you would expect. Such roundoff errors are caused by the fact that floating-point numbers are represented in the binary number system. There is no precise binary representation of the fraction 1/10, just as there is no accurate representation of the fraction 1/3 in the decimal system. If you need precise numerical computations without roundoff errors, use the BigDecimal class, which is introduced later in this chapter.
      

  11.   

    不过什么语言,计算机浮点数一般是遵循着同一个规范,计算时就有精度问题。
    你可以用java.math.BigDecimal。
      

  12.   

    x=0.999....
    x*10=9.999...=9+x;
    x=1;
      

  13.   

    import java.text.DecimalFormat;
        java.math.BigDecimal b1=new  java.math.BigDecimal(1.2);
        java.math.BigDecimal b2=new  java.math.BigDecimal(1.5);
        System.out.println(b1.multiply(b2));
        double num = b1.multiply(b2).doubleValue();
        String D1 = new DecimalFormat(".00").format(num);
        System.out.println(num);
        System.out.println(D1);