Why does the code given below Prints b on the Screen?
#include<stdio.h>
main()
{
float a = 5.6;
if(a == 5.6)
{
printf("a");
}
else
{
printf("b");
}
}
Why does the code given below Prints b on the Screen?
#include<stdio.h>
main()
{
float a = 5.6;
if(a == 5.6)
{
printf("a");
}
else
{
printf("b");
}
}
As floating point Numbers can't be matched exactly (because between each 2 numbers you choose are infinite other numbers). A machine can't represent them all and is forced to represent them with a moddel of only some floating point numbers it is able to represent.
So in your case, the system is probably not storing 5.6
because that's a number your machine doesn't want to represent. Instead it is storing something which is pretty close to 5.6
into the memory.
So if you do comparing with floating point numbers you never should check for equivalenz. Instead you should use the system C define FLT_EPSILON
and check for
if (((a - 5.6) > -FLT_EPSILON) && ((a - 5.6) < FLT_EPSILON))
{
...
}
Where FLT_EPSILON
is the smallest representable float type value.
So if the difference from a to 5.6 is absolute smaller as EPSILON, you can be sure it WAS equal, but the machine has chosen the next number it knows instead of 5.6
.
The same would be DBL_EPSILON for double type.
this types are defined in float.h
When you want a float value don't forget to add f
#include<stdio.h>
main()
{
float a = 5.6f;
if(a == 5.6f)
{
printf("a");
}
else
{
printf("b");
}
}
prints a
as expected.
The problem was that both 5.6
are defined as double
literals, and the a
got converted into a float
while in the if
it's still comparing it to a double
value so you get false.
Actually adding f
only inside the if would be enough, but better safe then sorry.
floating point number in c is double by default. If you want use as float you need to add f
at end of the number. try below code it gives a
#include<stdio.h>
main()
{
float a = 5.6;
if(a == 5.6f)
{
printf("a");
}
else
{
printf("b");
}