hofmn
hofmn

Reputation: 257

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

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

The result of a * b is -0, but I expected 0. Where did I go wrong?

Upvotes: 23

Views: 927

Answers (1)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361302

The bit representation of -0.0 and 0.0 are different, but they are same value, so -0.0==0.0 would return true. In your case, result is -0.0, because one of the operand is negative.

See this demo:

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

Output (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 

As you can see yourself, the last byte of -0.0 is different from the last byte of 0.0.

Hope that helps.

Upvotes: 31

Related Questions