Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Programming Basics [duplicate]

Tags:

c

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");    
    }
}
like image 766
Aamir Altaf Kathu Avatar asked May 08 '26 04:05

Aamir Altaf Kathu


1 Answers

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

like image 83
dhein Avatar answered May 09 '26 23:05

dhein