What's wrong with using == to compare floats in Java?

后端 未结 21 1903
你的背包
你的背包 2020-11-22 01:00

According to this java.sun page == is the equality comparison operator for floating point numbers in Java.

However, when I type this code:



        
21条回答
  •  名媛妹妹
    2020-11-22 01:40

    In addition to previous answers, you should be aware that there are strange behaviours associated with -0.0f and +0.0f (they are == but not equals) and Float.NaN (it is equals but not ==) (hope I've got that right - argh, don't do it!).

    Edit: Let's check!

    import static java.lang.Float.NaN;
    public class Fl {
        public static void main(String[] args) {
            System.err.println(          -0.0f   ==              0.0f);   // true
            System.err.println(new Float(-0.0f).equals(new Float(0.0f))); // false
            System.err.println(            NaN   ==               NaN);   // false
            System.err.println(new Float(  NaN).equals(new Float( NaN))); // true
        }
    } 
    

    Welcome to IEEE/754.

提交回复
热议问题