问题
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