How to compare two double values in Java?

后端 未结 7 1463
滥情空心
滥情空心 2020-11-22 13:10

A simple comparison of two double values in Java creates some problems. Let\'s consider the following simple code snippet in Java.

package doublecomparision;         


        
7条回答
  •  温柔的废话
    2020-11-22 13:46

            int mid = 10;
            for (double j = 2 * mid; j >= 0; j = j - 0.1) {
                if (j == mid) {
                    System.out.println("Never happens"); // is NOT printed
                }
    
                if (Double.compare(j, mid) == 0) {
                    System.out.println("No way!"); // is NOT printed
                }
    
                if (Math.abs(j - mid) < 1e-6) {
                    System.out.println("Ha!"); // printed
                }
            }
            System.out.println("Gotcha!");
    

提交回复
热议问题