Processing a double variable as boolean

What is the best way (efficiency / best practice) to check if a double variable is equal to 0?

    1. if(a_double)
          .....
       else
          .....

    OR

    2. if(a_double == 0)
          .....
       else
          .....
+3
source share
3 answers

The second is usually better (in more detail about what you are doing). I usually prefer if (a_double == 0.0). Also note that floating-point approximation comparisons are often useful given the possibility of rounding in calculations (although doing this well may be nontrivial).

. , , , : . , , , ​​. ( ) , 2, .

, ( ), (, IEEE , 1e + 10000 1e- 2000). , , (, double 1e-308 - 1e-300 7 ~ 15).

( - 2 53), , 2 (, 3,5, 1,375).

, / . , , , (.. 16 2, , 2). , 5 (, 1.2 , ). , ( , ) , , .

+7

. , .

#include<iostream>
using namespace std;
int main(){
double a=3/5;
double b=2/5;
double c=(a+b)-1;
if(c==0)
        cout<<"C is 0"<<endl;
else if(c==0.0)
        cout<<"C is 0.0"<<endl;
else
        cout<<"C!=0 && C!=0.0"<<endl; //This will print most of the time
}

- -

, , a_double . , @Jerry , == . , .

#include<iostream>
using namespace std;
int main(){
double a=5.5;
double b=6.5;
double c=(a+b)/12;
if(c==0)
        cout<<c<<endl;
else
        cout<<"c is not equal to 0"<<endl;
}
0

Source: https://habr.com/ru/post/1771421/


All Articles