为什么这种零比较不能正常工作?

HAL*_*000 3 c++ double c++11

我有这个代码:

double A = doSomethingWonderful(); // same as doing  A = 0;
if(A == 0)
{
    fprintf(stderr,"A=%llx\n", A);
}
Run Code Online (Sandbox Code Playgroud)

而这个输出:

A=7f35959a51c0
Run Code Online (Sandbox Code Playgroud)

这怎么可能?

我检查了7f35959a51c0的值,看起来像是6.91040329973658785751176861252E-310,它非常小,但不是零.

编辑:

好的我明白那种打印双精度值的方法不起作用.我需要找到一种方法来打印double的字节.

在评论后我修改了我的代码:

    A = doSomethingWonderful();// same as doing  A = 0;
    if(A == 0)
    {
        char bytes[8];
        memcpy(bytes, &A, sizeof(double));
        for(int i = 0; i < 8; i++)
        fprintf(stderr," %x", bytes[i]);
    }
Run Code Online (Sandbox Code Playgroud)

我得到这个输出:

0 0 0 0 0 0 0 0
Run Code Online (Sandbox Code Playgroud)

所以最后似乎比较工作正常,但我做的不好.

Dao*_*Wen 6

IEEE 754精度浮点值使用指数值中的偏差来完全表示正指数和负指数.对于双精度值,该偏差为1023 [源],恰好为0x3ff十六进制,与A您打印的十六进制值相匹配1,或0e0.


另外两个小笔记:

  • 打印字节时,您可以使用%hhx它来仅打印2个十六进制数字而不是符号扩展到8.
  • 您可以使用union将double值可靠地打印为8字节整数.
double A = 0;
if(A == 0)
{
    A = 1; // Note that you were setting A to 1 here!
    char bytes[8];
    memcpy(bytes, &A, sizeof(double));
    for(int i = 0; i < 8; i++)
        printf(" %hhx", bytes[i]);
}
int isZero;
union {
    unsigned long i;
    double d;
} u;
u.d = 0;
isZero = (u.d == 0.0);
printf("\n============\n");
printf("hex   = %lx\nfloat = %f\nzero?   %d\n", u.i, u.d, isZero);
Run Code Online (Sandbox Code Playgroud)

结果:

 0 0 0 0 0 0 f0 3f
============
hex   = 0
float = 0.000000
zero?   1
Run Code Online (Sandbox Code Playgroud)

所以在第一行中,我们看到的1.00e0(即0 0).

在下面的行中,我们看到当您使用union来打印double的十六进制值时0.0,您会得到0预期的结果.