为什么这个 java 计算浮动值位数的代码会为此值循环?

Why does this java code to count digit of floating value goes in loop for this value?

import java.util.Scanner;

class FloatDigit {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double n = sc.nextDouble();
        int x = (int) n;
        int count = 0;
        do {
            count++;
            x = x / 10;
        } while (x != 0);

        System.out.println("Before Decimal Digits: " + count); 
        //it gets stuck from here only

        do {
            count++;
            n = n * 10;
        } while (n != (int) n);
        System.out.println(count + " total digits present in there in number.");
    }
}

这将进入一个无限循环的值:58.2354/58.234。它也适用于其他值和更长的值。

如果在第二个循环中添加一些调试日志记录,可以看出,当 double 数字乘以 10 时,有一个小错误不允许比较 n == (int) n永远成为现实。

浮点运算存在一定的计算误差实际上是一个已知问题,因此在将double n与小数点右移的对应项进行比较时应注意:

do {
    count++;
    n = n * 10;
    System.out.println(count + " - " + n);
} while (Math.abs(n - (int) n) > 1E-7);

System.out.println(count + " total digits present in the number.");

输出:

58.234
Before Decimal Digits: 2
3 - 582.34
4 - 5823.400000000001
5 - 58234.00000000001
5 total digits present in the number.