为什么这个双值打印为“-0”?

时间:2013-04-17 18:46:51

标签: c++

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

a * b的结果是-0,但我期待0。我哪里出错了?

1 个答案:

答案 0 :(得分:31)

-0.00.0不同,但它们相同值,所以{ {1}}将返回-0.0==0.0。在您的情况下,trueresult,因为其中一个操作数为负数。

参见此演示:

-0.0

输出(demo@ideone):

#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);
}

正如您所见,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 last 字节与-0.0 last 字节不同。

希望有所帮助。