Thanks for the reply
But even the following code gives "Wrong".
int main(void)
{
float a = 0.7f;
if(a < 0.7)
printf("Wrong");
else
printf("God job");
return 0;
}
Unsurprisingly as a still has the value of 0.7 represented as a float
which
can be (and in this case is) smaller than 0.7 represented as a double.
try
int main(void)
{
float a = 0.7;
if(a < 0.7f)
printf("Wrong\n");
else
printf("Good job\n");
return 0;
}
or
int main(void)
{
float a = 0.7;
if(a < (double)((float)0.7))
printf("Wrong\n");
else
printf("Good job\n");
return 0;
}
I think the explanation that the declaration
float a = 0.7f;
is equivalent to
float a = (float)0.7;/*Conversion from double to float might truncate
the result*/
will work.
The expression '0.7f' forces the compiler to interpret 0.7 as a float
directly, rather than as a double converted to float as clearly stated
by the standard.
Yes, more precisely
According to the standard 0.7f must be the float value that best
approximates the
real number 0.7, or the second best or the third best. (float) 0.7
must be the
the float value that is the nearest value higher or the nearest value
lower to the value chosen for the double which
represents 0.7 (again the standard allows three possible choices).
So 0.7f does not have to equal (float)0.7 (however, Karnac is willing
to
bet that it does).
So this explanation will fail.
So an explanation as you stated above, will work.
That is, the float value 0.7f can (very probably) not be represented
exactly as a float.
No 0.7f (approx 0.699999988 on my machine)
is a possible float value
so it can with certainty be represented exactly as a float.
It is the real number 0.7 that ( very probably) can't be represented
exactly as a float. And very probably, the float value used to
represent the real number 0.7 (whether selected as 0.7f or as
(float)0.7)
will be smaller that the double value used to represent the
real number 0.7.
My question in this context is:
How this inaccurate representation complies with ANSI standards
The ANSI standards do not impose the restriction that every
decimal value be representable as a float and/or double
(this is not possible using base 2) or that every double value
be representable as a float value (this is usually not possible).
In general the float value used to represent x can be greater
than, less than or equal to the double value used to represent x.
(try 0.8, 0.7 and 0.5)
- William Hughes