浮点数转化为精确的二进制浮点数

算法描述:将浮点数左移一位,依次获取每一位,追加到StringBuider里,当StringBuilder长度大于34位时(即浮点数大于32),该数无法用二进制精确表示,输出ERROR,否则则将结果输出。

import java.util.Scanner;

public class Test4 {
    public static void main(String[] args) {
        /**
         * 将浮点数转化为精确的二进制浮点数,并且输出
         * 若无法精确转化,则输出ERROR
         */
        Scanner in = new Scanner(System.in);
        double d = in.nextDouble();
        String str = isExactNumber(d);
        if(str==null) {
            System.out.println("ERROR!!!");
        }else{
            System.out.println(str);
        }
    }
    public static String isExactNumber(double d) {
        StringBuilder stringBuilder = new StringBuilder("0.");
        while (d != 0) {
            d *= 2;
            if (d >= 1) {
                stringBuilder.append(1);
                d -= 1;
            } else {
                stringBuilder.append(0);
            }
            if (stringBuilder.length() > 34) {
                return null;
            }
        }
        return stringBuilder.toString();
    }
}

github地址:https://github.com/lcl0512/algorithm-in-java.

发布了12 篇原创文章 · 获赞 5 · 访问量 652

猜你喜欢

转载自blog.csdn.net/qq_43657590/article/details/103938769