相同的浮点值作为比较不相等 [英] Identical float values comparing as inequal
问题描述
我在做一些'确定'的输出在C问题我遇到了这个问题,它看着它的脸很简单,但在运行code后,给我留下了疑惑。
我的预期产量为真。但是一旦运行,这是假。而当我检查的值f用printf(),它表现出0.1。是否有人可以解释为什么f为0.1分配不为IF语句返回true?
有是从那里我拿起这个问题了答案没有解释,我是不是能够找到一个答案我自己。
的#include<&stdio.h中GT;诠释的main()
{
浮动F = 0.1;
如果(F = = 0.1)
的printf(真);
其他
的printf(假);
}
的问题是,变量˚F
定义为具有类型浮动
而浮动恒 0.1
的类型为双击
。键入双击
有更多的precision类型不是浮动
。它有更多的二进制数字来重新present部分。因此,在这个声明
浮动F = 0.1;
有一个截断。
要得到你应该写预期的结果至少
如果(F == 0.1F)
此外,要确保没有四舍五入code看起来应该
的#include<&stdio.h中GT;INT主要(无效)
{
浮动F = 0.1F; 如果(F == 0.1F)
的printf(真\\ n);
其他
的printf(假\\ n);
}
I was working on some 'determine the output' questions in C. I came across this question which looked simple on the face of it, but after running the code left me puzzled.
The output I expected was "True". However upon running, it was "False". And when I checked the value of f using printf(), it showed 0.1. Can someone please explain why f being assigned 0.1 doesn't return true for the IF statement?
There was no explanation for the answer from where I picked the question up, and I wasn't able to find an answer myself.
#include <stdio.h>
int main()
{
float f = 0.1;
if (f == 0.1)
printf("True");
else
printf("False");
}
The problem is that variable f
defined as having type float
while float constant 0.1
has type double
. Type double
has more precision than type float
. it has more binary digits to represent fraction. So in this statement
float f = 0.1;
there is a truncation.
To get the expected result you should write at least
if (f == 0.1f)
Also that to be sure that there is no rounding the code should look as
#include <stdio.h>
int main( void )
{
float f = 0.1f;
if ( f == 0.1f )
printf("True\n");
else
printf("False\n");
}
这篇关于相同的浮点值作为比较不相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!