设置为0.1 A浮动比较反对虚假0.1 [英] A float set to 0.1 compares false against 0.1
本文介绍了设置为0.1 A浮动比较反对虚假0.1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
int main()
{
float f = 0.1;
if (f == 0.1)
printf("True");
else
printf("False");
}
我只是在C初学者。我不明白上面的程序的行为。输出是假的。为什么?
I am just a beginner in c. I don't understand the behavior of the above program. The output is false. Why??
推荐答案
0.1
是双击
文字。
由于 0.1
不能重新$ P $浮点psented确切地说,一个浮动
设置为0.1将比较打击虚假一个双击
设置为0.1。
As 0.1
cannot be represented exactly in floating point, a float
set to 0.1 will compare false against a double
set to 0.1.
您比较会表现,如果你使用浮动
字面意为: 0.1F
(注意后缀˚F
:不要与你的变量名称混淆):
Your comparison would behave as intended if you use a float
literal: 0.1f
(note the suffixed f
: not to be confused with your variable name):
float foo /*renamed for clarity*/= 0.1;
if (foo == 0.1f){
/*this will compare true*/
这篇关于设置为0.1 A浮动比较反对虚假0.1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文