Why is the output different in both cases comparing floats

本秂侑毒 提交于 2020-06-17 08:03:32

问题


PYTHON PROGRAM:

a = 0.2
if a == 0.2:
    print('*')

OUTPUT:

*

C PROGRAM:

#include <stdio.h>

int main(void) 
{
    float a = 0.2;
    if(a == 0.2)
    {
        puts("*");
    }
}

OUTPUT:


Why is the output different in both cases? Is there a difference between the working of == operator?


回答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>

int main(void) 
{
    float a1 = 0.2;

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

    double a2 = 0.2;

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

Its output is

*
*


来源:https://stackoverflow.com/questions/62394140/why-is-the-output-different-in-both-cases-comparing-floats

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!