views:

389

answers:

7
#include <iostream>
using namespace std;

int main()
{
    double u = 0;
    double w = -u;
    cout << w << endl;
    return 0;
}

Why does this great piece of code outputs "-0" and not "0", as one would expect?

+13  A: 

The IEEE 754 standard for floating-point numbers has the sign bit separate from the mantissa, which allows for zero to be negative. Wikipedia should be able to help explain this.

foxxtrot
+1  A: 

Because "negative zero" is a valid number!

http://en.wikipedia.org/wiki/%E2%88%920_(number)

clintp
+1  A: 

Take a look at this article: http://en.wikipedia.org/wiki/Floating_point. Note that there is a sign bit, even if the value is zero.

Trent
+2  A: 

In IEEE floating point 0 and -0 are both distinct values, from here under "Special Values":

Note that -0 and +0 are distinct values, though they both compare as equal.

Doug T.
+2  A: 

The IEEE 754 standard for floating point arithmetic makes a distinction between +0 and -0, this can be used when dealing with very small numbers rounded to zero where the sign still has an importance.

Drealmer
+1  A: 

Because a double can indeed have values -0, +0, -infinity, +infinity and NaN, which can be a result of various interesting expressions, like 0/0.

Look here for more information.

Saulius
+1  A: 

Because your expectations are wrong.

IEEE requires that positive and negative zero be represented seperately.

That is what you're seeing here.