I have to be able to sort negative zeros and zeros for an assignment i am doing at university using c++, could someone tell me why the following code does produce a negative zero? i'm stuck and i am not sure why this works...
cout << "Enter the number of elements you want to add to the vector:\n";
cin >> x;
cout << "Enter the integers: \n" << endl;
for (int i = 0; i < x; i++)
{
cin >> y;
y = y - 0.0;
cout << y;
Array.push_back(y);
}
If there is a better way of producing a negative zero when sorting the above vector please advise. Many thanks!
First of all, there need not be any negative zeroes in standard C++, so I assume you are talking about the negative zero from IEEE-754, which is what most (I never encountered an exception) C++ implementations base their floating point math on.
In this case, the expression
will yield
-0.0
only if eithery == -0.0
before that assignment or if you set your rounding mode to "round towards -INFINITY", which you usually won't.To actually produce a
double
with the value-0.0
, you can just assign the desired value:Now
d == -0.0
in IEEE floating point math.However, as
(IEEE 754-1985, 5.7. Comparison),
-0.0 < 0.0
will yieldfalse
, so if you actually want to sort negative zero before positive zero, you will need to write your own comparator, possibly usingstd::signbit
.Appendix: Relevant standard quote:
IEEE 754-1985, 6.3 (The Sign Bit)