Understanding float variable comparisons in if ()

Unable to find the reason for the following code snippet:

#include <stdio.h> int main() { float f = 0.1; if (f == 0.1) printf("True"); else printf("False"); return 0; } 

The conclusion is false.

 #include <stdio.h> int main() { float f = 0.1; if (f == (float)0.1) printf("True"); else printf("False"); return 0; } 

The correct output is now displayed. What is the reason for this?

And what is the reason for this behavior.

 #include <stdio.h> main() { int n = 0, m = 0; if (n > 0) if (m > 0) printf("True"); else printf("False"); } 
-2
source share
2 answers

0.1 literal double . Here you lose the precision float f = 0.1;

We can say that we again lose accuracy during the comparison, so why not f == 0.1 true anyway? Because float extends to double , and not vice versa. In C, the smaller type always extends to the larger.

A simplified example, we can say that double(float(1.0)) != 1.0

Possible solutions:

  • use double instead of float as type f .
  • use listing as in your second example
  • use float literals - replace all 0.1 with 0.1f

The best solution

Floating point variables have many problems when comparing. They, including this one, can be solved by defining your own comparison function:

 bool fp_equal(double a, double b, double eps = FLT_EPSILON) { return fabs(a - b) < fabs(eps * a); } 

The second part of the question:

Why the answer is incorrect, because the else part always matches the innermost if block. So you were confused by formatting, the code is equivalent:

 #include <stdio.h> int main() { int n = 0, m = 0; if (n > 0) { if (m > 0) { printf("True"); } else { printf("False"); } } } 
+5
source

Answer the second question (third example):

According to your digression, the code does not do what you exepect it to:

 #include <stdio.h> main() { int n = 0, m = 0; if (n > 0) if (m > 0) printf("True"); else printf("False"); } 

Here else belongs to the inner if , so it equals

 #include <stdio.h> main() { int n = 0, m = 0; if (n > 0) { if (m > 0) { printf("True"); } else { printf("False"); } } } 

but I think you meant:

 #include <stdio.h> main() { int n = 0, m = 0; if (n > 0) { if (m > 0) { printf("True"); } } else { printf("False"); } } 

This is a good example of why you need to specify custom parentheses in if .

+2
source

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


All Articles