Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 750
hofmn Avatar asked Apr 17 '13 18:04

hofmn


People also ask

How do you print double value?

We can print the double value using both %f and %lf format specifier because printf treats both float and double are same. So, we can use both %f and %lf to print a double value.

Is 0 a double in C++?

A literal 0 is considered to be an int literal; literal 0.0 is a double literal. When assigning to a double , either will work (since the int can be cast in a widening conversion); however, casting 0.0 to an int is a narrowing conversion, and must be done explicitly; i.e. (int)0.0 .


1 Answers

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.

like image 199
Nawaz Avatar answered Sep 20 '22 09:09

Nawaz