Comparison of variables of type double and 0

Double type variable is compared with 0

overview

We always encounter comparisons between double type variables and 0 every day. It is directly compared with 0 in non-strict cases, but in fact this is a wrong way of writing. double is a double-precision type, which generally reserves 15 as a decimal. The Flaot single-precision type generally retains 6 as a decimal. Therefore, it cannot be directly compared with 0. Although sometimes you can get the result you want, it is not rigorous.

accomplish

Here choose a relatively small number 1e-8, and take its approximate number to compare with the double type variable.

double type

double type is equal to 0

double a = 4.343564;
if(fabs(a - 0) < 1e-8 ){
    
    } //相当于a > -(1e-8) && a < 1e-8

double type is greater than 0

double a = 4.343564;
if(a > 1e-8 ){
    
    }

double type is less than 0

double a = 4.343564;
if(a < -(1e-8) ){
    
    } 

double type is not equal to 0

double a = 4.343564;
if(fabs(a - 0) > 1e-8 ){
    
    } //相当于a < -(1e-8) && a > 1e-8

Just for the record, if there is something wrong, please point it out.

Guess you like

Origin blog.csdn.net/blqzj214817/article/details/128376525