Reputation: 53
#include <stdio.h>
int main() {
float a = 0.7;
int c;
c = a < 0.7;
printf("%d", c);
}
Output printed is 1 though it is printing 0 for all cases except 0.7,7.7 and 0.9, why it is so??? Also it should be 0 because precedence of '<' operator is more than '=' operator
Upvotes: 2
Views: 146
Reputation: 120239
0.7 cannot be represented exactly as a float
value, so a
stores some approximation of it. The gotcha here is that the literal 0.7 has type double
, so a more precise approximation of 0.7 is used to represent it. That approximation may differ from the less precise one in either direction.
To fix, use a double
variable, or a float
literal 0.7f
.
Upvotes: 13
Reputation: 27577
Your basically dealing with the fact that 0.1
is a repeating decimal in binary. So things that look nice and clean as literals (i.e. 0.7
) can't be represented exactly. Coupled with this you're mixing types since the literal 0.7
is a double
.
Upvotes: 0