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"); } } }
source share