为什么这个双精度值打印为 "-0" ?

Why is this double value printed as "-0"?

本文关键字:打印 双精度 为什么      更新时间:2023-10-16
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最后一个字节不同。

希望对你有帮助。