#include <stdio.h>
int main(void)
{
float c;
c = 4.7;
if(c == 4.7)
{
printf("Hello World");
}
return 0;
}
The problem here is with the float data type... To print Hello world we need to write (float)4.7 why??
#include <stdio.h>
int main(void)
{
float c;
c = 4.7;
if(c == 4.7)
{
printf("Hello World");
}
return 0;
}
The problem here is with the float data type... To print Hello world we need to write (float)4.7 why??
4.7
has the type double
, and c
has the type float
. If you compare a float
and a double
, the float
first gets converted to a double
. So your if
is doing: (double)(float)4.7 == 4.7
, which is false, because when converting 4.7
to float
there was a loss of precision, and the number changed a tiny bit.
You can do an approximate comparison like this if (fabs(f - 4.7) < 1e-10)
.