c++ - Floating point comparison -


this question has answer here:

int main() {     float = 0.7;     float b = 0.5;     if (a < 0.7)     {        if (b < 0.5) printf("2 right");        else         printf("1 right");     }     else printf("0 right"); } 

i have expected output of code 0 right. dismay output 1 right why?

int main() {     float = 0.7, b = 0.5; // these floats     if(a < .7)              // double     {       if(b < .5)            // double         printf("2 right");       else         printf("1 right");     }     else       printf("0 right"); } 

floats promoted doubles during comparison, , since floats less precise doubles, 0.7 float not same 0.7 double. in case, 0.7 float becomes inferior 0.7 double when gets promoted. , christian said, 0.5 being power of 2 represented exactly, test works expected: 0.5 < 0.5 false.

so either:

  • change float double, or:
  • change .7 , .5 .7f , .5f,

and expected behavior.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -