Sorting between signed and unsigned zeros c++

422 Views Asked by At

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!

1

There are 1 best solutions below

0
On

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

y = y - 0.0;

will yield -0.0 only if either y == -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:

double d = -0.0;

Now d == -0.0 in IEEE floating point math.

However, as

Comparisons shall ignore the sign of zero

(IEEE 754-1985, 5.7. Comparison), -0.0 < 0.0 will yield false, so if you actually want to sort negative zero before positive zero, you will need to write your own comparator, possibly using std::signbit.


Appendix: Relevant standard quote:

When the sum of two operands with opposite signs (or the difference of two operands with like signs) is exactly zero, the sign of that sum (or difference) shall be + in all rounding modes except round toward –INFINITY, in which mode that sign shall be –.

IEEE 754-1985, 6.3 (The Sign Bit)