Is checking a double for equality ever safe?

前端 未结 5 1197
时光说笑
时光说笑 2020-12-03 04:42

I have the following code:

double x = 0;

{ ...do stuff ...}

if(x == 0){

}

I was always taught that you shouldn\'t check floats for equal

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 05:33

    if you set it yourself and wish to see if it ever changed you can safely check for equality (like using a sentinel value) though NaN is safer for things like that

    float x=Float.NaN;
    {
       //some code that may or may not set x
    }
    if(Float.isNaN(x))//it never got set
    

提交回复
热议问题