double a = 0;
double b = -42;
double result = a * b;
cout << result;
a * b的结果是-0,但是我期望0。我哪里做错了?

最佳答案

-0.00.0的位表示形式不同,但它们的相同,因此-0.0==0.0将返回true。在您的情况下,result-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的最后一个字节不同。

希望能有所帮助。

关于c++ - 为什么将此 double 值打印为 “-0”?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16067753/

10-11 22:54