public static void main(String args[]) {
        double s=0;
         int[] a = { 0, 0, 0, 0, 0, 0, 0, 0 };
        double[] b = { 2.00, 1.00, 0.50, 0.20, 0.10, 0.05, 0.02, 0.01 };
         double r=4;
        double l = r /100;
        s = 5.00 - l;
        for (int i = 0; i < 8; i++) {
            while (s != 0 && s > b[i]) {
            
                s = s - b[i];
                a[i]++;
            }
            System.out.println(s);
        }
为什么显示的结果是
0.96
0.96
0.45999999999999996
0.05999999999999994
0.05999999999999994
0.00999999999999994
0.00999999999999994
0.00999999999999994 

解决方案 »

  1.   

    这是double类型的精度问题!
    小数点后面精确到17位!
      

  2.   

    double n=0.96-0.5,m=0.46-0.2,p=0.8-0.5,w=0.7-0.5,x=0.6-0.5;
              double q=n-0.2;
              System.out.println(n);
              System.out.println(m);
              System.out.println(p);
              System.out.println(q);
              System.out.println(w);
              System.out.println(x);
    输入结果是:
    0.45999999999999996
    0.26
    0.30000000000000004
    0.25999999999999995
    0.19999999999999996
    0.09999999999999998神奇,也想知道为什么
      

  3.   

    其次这是java底层的运算机制!
    它会自动的精确到17位!
    如果我们要求要精确到几位小数,可以用DecimalFormat来做处理! import java.text.*;public static void main(String args[]) {
            double s=0;
             int[] a = { 0, 0, 0, 0, 0, 0, 0, 0 };
            double[] b = { 2.00, 1.00, 0.50, 0.20, 0.10, 0.05, 0.02, 0.01 };
             double r=4;
            double l = r /100;
            s = 5.00 - l;
            DecimalFormat df = new DecimalFormat("0.00");//可以格式化这个double类型的数
            for (int i = 0; i < 8; i++) {
                while (s != 0 && s > b[i]) {
                    
                    s = s - b[i];
                    a[i]++;
                }
                System.out.println(df.format(s));
     }
      

  4.   

    我知道double精确到17位
    可是为什么0.96不是17位啊
      

  5.   

    可以去分析下JAVA源代码:
    这是Double类toString()方法,
    import sun.misc.FloatingDecimal;
        public static String toString(double d) {
    return new FloatingDecimal(d).toJavaFormatString();
        }估计就是上面的底层实现的导致结果不同。
      

  6.   

    如果牵涉到小数点计算,尽量不要用float,double,精度不准确,最好用BigDecimal,尤其是有关产量及money的的计算;