23
double a = 0;
double b = -42;
double result = a * b;
cout << result;

结果a * b-0,但我意料之中0。我哪里做错了?

4

1 回答 1

31

和的位表示不同,但它们的值相同,所以会返回。在您的情况下,is ,因为其中一个操作数是负数。-0.00.0-0.0==0.0trueresult-0.0

看这个演示:

#include <iostream>
#include <iomanip>

void print_bytes(char const *name, double d)
{
    unsigned char *pd = reinterpret_cast<unsigned char*>(&d);
    std::cout << name << " = " << std::setw(2) << d << " => ";
    for(int i = 0 ; i < sizeof(d) ; ++i)
       std::cout << std::setw(-3) << (unsigned)pd[i] << " ";
    std::cout << std::endl;
}

#define print_bytes_of(a) print_bytes(#a, a)

int main()
{
    double a = 0.0;
    double b = -0.0;

    std::cout << "Value comparison" << std::endl;
    std::cout << "(a==b) => " << (a==b)  <<std::endl;
    std::cout << "(a!=b) => " << (a!=b)  <<std::endl;


    std::cout << "\nValue representation" << std::endl;
    print_bytes_of(a);
    print_bytes_of(b);
}

输出(demo@ideone):

Value comparison
(a==b) => 1
(a!=b) => 0

Value representation
a =  0 => 0 0 0 0 0 0 0 0 
b = -0 => 0 0 0 0 0 0 0 128 

如您所见, 的最后一个字节与 .-0.0最后一个字节不同0.0

希望有帮助。

于 2013-04-17T18:49:59.347 回答