That's complicated, but in this case it revolves around what numbers actually are.
When you type "1.1" as a number, what type of number is that? We know it's not an integer - because it has a fractional component - so it's a floating point number of some form, but what "size" of floating point number is that? Does it matter?
In C there are two ways to store floating point numbers:
float
and
double
(well ... technically there are three:
long double
is also available) and the difference is no much space they take up.
float
values generally occupy 4 bytes, and
double
take 8 becuase they can contain more precise values.
But what is 1.1 as far as the compiler is concerned? Answer: it's a
double
because that's "the most accurate" and it gets an implicit cast down to
float
when you do the assignment.
Does it matter? Yes. Because floating point numbers aren't stored as "one one and a point one as well", they are stored in a much more complicated way:
Single-precision floating-point format - Wikipedia[
^] goes into the details, but becuase it's all bionary instead of base ten, 1.1 doesn't store as an "accurate" number - it's different. And the
double
version isn't the same as the
float
version because it can store more binary digits.
The simple solution is to stick to one format:
int main()
{
float x = 1.1;
while(x == 1.1F)
{
printf("%f\n",x);
x = x - 0.1F;
}
return 0;
}
Or
int main()
{
double x = 1.1;
while(x == 1.1)
{
printf("%f\n",x);
x = x - 0.1;
}
return 0;
}
And it'll do what you expect.