Java Denary到二进制转换器精度建议

时间:2017-11-08 09:47:37

标签: java binary decimal precision fractions

我还在学习java,我正在对这个转换器进行练习。我写了下面的内容,它有效。一个矿工的问题是,当它转换小的小数部分时,它将具有通常的精度问题(我理解,所以我打印出它实际用于计算的分数)。我发现大多数在线或应用程序转换器都使用以下方法之一处理此问题:

  1. 限制用户输入及其输出的小数空间
  2. 按原样输出不准确的结果
  3. 我想知道当使用具有轻微精度问题的转换器时人们如何看待这个问题。它有什么关系吗?反正有没有解决这个问题呢?请分享你的想法。谢谢^^

    private static void DtoB() {
        int power;
        long i, integer;
        double d, fraction, f;
        System.out.println();
        System.out.print("Plese enter the denary number: ");
        //Break the number
        d = getDouble();    //method that gets the valid input form user
        integer = Math.abs((long)d);
        fraction = Math.abs(d - integer);
        i = integer;        //store the original input for later use
        f = fraction;       //store the original input for later use
        power = 1;
    
        System.out.println("Integer part: "+i);
        System.out.println("Fraction part: "+f);
        System.out.println();
        System.out.print("The binary form is: ");
    
        //Convert the integer part
        //get the largest power of 2 smaller than the number
        while(integer != 0) {
            while(power <= integer/2) { 
            power *= 2;
            }
            System.out.print("1");
            integer -= power;
            //get the rest 1 & 0 till the smallest power of 2
            while(power > 1) {
                power /= 2;
                if (integer < power)
                    System.out.print("0");
                else {
                    System.out.print("1");
                    integer -= power;
                }
            }
        }
        //Convert the fraction part
        if (fraction < 1.0){   //check if there is a fraction part needs to convert
            System.out.print(".");
            while (fraction < 1.0 && fraction != 0) {
                fraction *= 2;
                if (fraction > 1.0) {
                    System.out.print("1");
                    fraction = (fraction - 1);
                }
                else {
                    System.out.print("0");
                }
            }
        }
        else if (fraction == 0) {
        }
    System.out.println();
    }
    

1 个答案:

答案 0 :(得分:0)

您拥有该要求,因此您可以接受。如果你是为客户写的,当然你会问他们。

为避免浮点精度问题,请完全避免使用浮点类型。

BigDecimal类用于在Java中执行任意精度数学。

如果出于学习原因,您不想使用BigDecimal,那么您可以自己编写类似的功能。以字符串形式读入您的号码。将其拆分为.以获取整数部分和小数部分,并将它们转换为整数。

您还需要跟踪小数部分中的前导零 - 否则3.513.00051会评估相同的内容。所以,例如:

  • 3.51解析为i==3, f==51, z==0
  • 42.0022解析为i=42, f==22, z==2

转换为二进制文件,我留给你作为练习。