c语言是2 = 2.00。当出现浮点不等式时 [英] Is 2=2.00 in c language .when do floating point inequality arise
问题描述
#include< stdio.h>
int main()
{
if(2 == 45.000 / 22.5)
printf(%d,1);
返回0;
}
以下程序打印1.
所以是2 == 2.0在c语言中被视为真。
如果它是真的如果我写2 ==(a / b)
其中a / b结果是2.00000005
如果我的编译器精度高达6位小数那么它会被视为真吗?
#include< stdio.h>
int main()
{
if(2 == 2.000000000001)
printf(%d,1);
返回0;
}
这不打印任何东西,但如果我输入2 == 2.000000000000000000000001则打印1。
谢谢
#include<stdio.h>
int main()
{
if(2==45.000/22.5)
printf("%d",1);
return 0;
}
the following program printed 1.
so is 2==2.0 treated as true in c language.
if its true what if i write 2==(a/b)
where a/b turns out to be something like 2.00000005
and if my compilers precision is upto 6 decimals then will it be treated as true?
#include<stdio.h>
int main()
{
if(2==2.000000000001)
printf("%d",1);
return 0;
}
this is not printing anything but if i type 2==2.000000000000000000000001 then 1 is being printed.
thanks
推荐答案
这是精确的。
当你使用==来比较两个值时,它们必须完全相同才能匹配:所以你不会期望一些东西g你好那里的台词。完全匹配你好!当你来到数字时它是一样的。
编译时
It's down to precision.
When you use == to compare two values, they have to be exactly the same to match: so you wouldn't expect something along the lines of "hello there." to exactly match "hello there!" and when you come to numbers it's the same.
when you compile
if(2==45.000/22.5)
编译器查看代码并且:它要
The compiler looks at teh code and:it to
45.000 - floating point constant value, 45.0
22.5 - floating point constant value, 22.5
So change to constant value: 45.0/22.5
if(2==2.0)
2 integer constant value: cast to floating point constant value, 2.0
if(2.0==2.0)
constant comparison: evaluate - true. Remove comparison if optimized
比较下一个值时
When you compare the next values
if(2==2.000000000001)
2.000000000001 - floating point constant value, 2.000000000001
2 - integer constant value, cast to float 2.0
if(2.0==2.000000000001)
constant comparison: evalutate - false. Remove comparison if optimized
当你尝试第三个:
When you try your third:
if(2==2.000000000000000000000001)
同样的事情发生了,但是当它将2.000000000000000000000001评估为浮点数时,没有足够的数字在浮点数的二进制表示中包含尾随的1,因此它的计算结果为2.0。
浮点数必须在32或者内部64位(有时是128位)二进制值,如果没有足够的位,它将被截断。
有一个好的(如果是技术性的) Wiki上的描述: Single-precision_floating-point_format [ ^ ]
这篇关于c语言是2 = 2.00。当出现浮点不等式时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!