Unable to find the reason for the following piece of code:
#include <stdio.h>
int main()
{
float f = 0.1;
if (f == 0.1)
printf("True");
else
printf("False");
return 0;
}
The output is false.
#include <stdio.h>
int main()
{
float f = 0.1;
if (f == (float)0.1)
printf("True");
else
printf("False");
return 0;
}
Now shows the correct output. Whats the reason behind this?
Also what is the reason of this behavior.
#include <stdio.h>
main()
{
int n = 0, m = 0;
if (n > 0)
if (m > 0)
printf("True");
else
printf("False");
}
0.1
literal isdouble
. You loose precision herefloat f = 0.1;
You could say we loose precision during comparison again, so why isn't
f == 0.1
true anyway? Becausefloat
extends todouble
, not the opposite. In C smaller type always extends to the bigger one.Simplified your example we can say that
double(float(1.0)) != 1.0
Possible solutions:
double
instead offloat
as a type off
.float
literals - replace all0.1
with0.1f
Better solution
Floating point variables have a lot of problems with comparisons. They, including this one, can be solved by defining your own comparison function:
The second part of the question:
Why the answer is false is because
else
part always corresponds to the innermostif
block. So you were confused by formatting, the code is equivalent to:Answer to your second question (third example):
According to your indention, the code doesn't do what you exepect it to:
Here the
else
belongs to the innerif
, so it's equal tobut I think you meant:
It's a good example for why one should alwys user brackets in
if
statements.