Reputation: 43
#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 output -0
and not 0
, as one would expect?
Upvotes: 4
Views: 1461
Reputation: 5696
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.
Upvotes: 2
Reputation: 65649
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.
Upvotes: 2
Reputation:
Because your expectations are wrong.
IEEE requires that positive and negative zero be represented seperately.
That is what you're seeing here.
Upvotes: 1
Reputation: 7207
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.
Upvotes: 1
Reputation: 13497
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.
Upvotes: 1
Reputation: 13209
Because "negative zero" is a valid number!
http://en.wikipedia.org/wiki/%E2%88%920_(number)
Upvotes: 1