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?
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With