Skip to content Skip to sidebar Skip to footer

Why Is The Output Different In Both Cases Comparing Floats

PYTHON PROGRAM: a = 0.2 if a == 0.2: print('*') OUTPUT: * C PROGRAM: #include int main(void) { float a = 0.2; if(a == 0.2) { puts('*');

Solution 1:

It is because the types float and double have different width reserved for the mantissa. The type double can represent a floating number more precisely. In this case that matters as 0.2 can't be represented exactly and has a very slightly different representation when stored as a double vs. a float.

In the condition

if(a == 0.2)

the left operand has the type float while the right operand has the type double, as the default type of a number literal with a "." in C is a double.

So change the declaration the following way

double a = 0.2;

Or alternatively change the condition like

if(a == 0.2f)

Here is a demonstrative program

#include<stdio.h>intmain(void){
    float a1 = 0.2;

    if ( a1 == 0.2f )
    {
        puts( "*" );
    }

    double a2 = 0.2;

    if ( a2 == 0.2 )
    {
        puts( "*" );
    }
}

Its output is

**

Post a Comment for "Why Is The Output Different In Both Cases Comparing Floats"