HAL*_*000 15 c c++ floating-point
我了解到比较双重使用==并不是明智的做法.但是我想知道检查双重是否已经初始化可能是危险的.例如,知道变量doubleVar如果已初始化则不能为零,这样做是否安全?
Foo::Foo(){
doubleVar = 0.0; // of type double
}
void Foo::Bar(){
if(doubleVar == 0){ // has been initialized?
//...
}else{
//...
}
}
Run Code Online (Sandbox Code Playgroud)
oua*_*uah 15
在IEEE-754中,长话短说:
double d;
d = 0.0;
d == 0.0 // guaranteed to evaluate to true, 0.0 can be represented exactly in double
Run Code Online (Sandbox Code Playgroud)
但
double d;
d = 0.1;
d == 0.1 // not guaranteed to evaluate to true
Run Code Online (Sandbox Code Playgroud)