C IEEE-Floats inf等于inf [英] C IEEE-Floats inf equal inf
问题描述
这个程序打印出equal:...(至少在Linux下,使用gcc的AMD64),在我看来它应该打印出不同的:... / p>
#include< stdio.h>
#include< stdlib.h>
int main(void)
{
volatile double a = 1e200; //使用volatile来抑制编译器警告
volatile double b = 3e200;
volatile double c = 1e200;
double resA = a * c; // resA和resB应该由inf
double resB = b * c;
if(resA == resB)
{
printf(equal:%e *%e =%e =%e =%e *%e \\\
,a,c ,RESA,RESB,b,C);
}
else
{
printf(different:%e *%e =%e!=%e =%e *%e \\\
,a,c ,resA,resB,b,c);
}
return EXIT_SUCCESS;
$ b另一个例子,为什么我认为inf和inf不一样,是:自然数和有理数都是无限的,但不一样。
那么,为什么inf == inf?解决方案 Infinities比较平等,因为这就是标准所说的。 5.11节比较谓词的细节:
lockquote
无穷操作数的相同符号应该比较相等。
In C, on a implementation with IEEE-754 floats, when I compare two floating point numbers which are NaN, it return 0 or "false". But why do two floating point numbers which both are inf count as equal?
This Program prints "equal: ..." (at least under Linux AMD64 with gcc) and in my opinion it should print "different: ...".
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
volatile double a = 1e200; //use volatile to suppress compiler warnings
volatile double b = 3e200;
volatile double c = 1e200;
double resA = a * c; //resA and resB should by inf
double resB = b * c;
if (resA == resB)
{
printf("equal: %e * %e = %e = %e = %e * %e\n",a,c,resA,resB,b,c);
}
else
{
printf("different: %e * %e = %e != %e = %e * %e\n", a, c, resA, resB, b, c);
}
return EXIT_SUCCESS;
}
A other example, why I think inf is not the same as inf, is: the numbers of natural numbers and rational numbers, both are infinite but not the same.
So why is inf == inf?
解决方案 Infinities compare equal because that's what the standard says. From section 5.11 Details of comparison predicates:
Infinite operands of the same sign shall compare equal.
这篇关于C IEEE-Floats inf等于inf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!