问题描述
PYTHON程序:
a = 0.2
,如果a == 0.2:
print('*')
输出:
*
C程序:
#include< stdio.h>
int main(void)
{
float a = 0.2;
if(a == 0.2)
{
puts( *);
}
}
输出:
为什么两种情况下的输出都不同? ==
运算符的工作方式之间有区别吗?
这是因为float和double类型为尾数保留了不同的宽度。 double类型可以更精确地表示一个浮点数。在这种情况下,重要的是0.2不能精确表示,并且存储为double和float时,表示形式略有不同。
在这种情况下
如果(a == 0.2)
左操作数的类型为float,而右操作数的类型为double,这是带有。的数字文字的默认类型。因此,按以下方式更改声明
双倍a = 0.2;
或者更改条件,例如
if(a == 0.2f)
这是一个示范程序
#include< stdio.h>
int main(void)
{
float a1 = 0.2;
if(a1 == 0.2f)
{
puts( *);
}
double a2 = 0.2;
if(a2 == 0.2)
{
puts( *);
}
}
其输出为
*
*
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?
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
*
*
这篇关于为什么在比较浮点数的两种情况下输出都不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!