如果先前将double初始化为零,那么将double比较为零是正确的吗?
我了解到使用==
比较双重不是明智的做法。 但是我想知道检查双重是否已经初始化可能是危险的。 例如,知道变量doubleVar如果已初始化则不能为零,这样做是否安全?
Foo::Foo(){ doubleVar = 0.0; // of type double } void Foo::Bar(){ if(doubleVar == 0){ // has been initialized? //... }else{ //... } }
在IEEE-754中,长话短说:
double d; d = 0.0; d == 0.0 // guaranteed to evaluate to true, 0.0 can be represented exactly in double
但
double d; d = 0.1; d == 0.1 // not guaranteed to evaluate to true