-3

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!

Ryan
  • 51
  • 1
  • 4
  • 1
    Can you please provide a [MCVE]. What are the types of `x` and `y` actually? – πάντα ῥεῖ Feb 07 '16 at 22:42
  • 2
    How are x and y defined? – cen Feb 07 '16 at 22:44
  • I'm reasonably sure that C++ by standard does not define what gives negative zero, and it's an implementation detail whether the hardware actually HAS negative zero or not. In other words, the result of your code, and whether negative zero is generated or not depends on the compiler and the processor targetted. – Mats Petersson Feb 07 '16 at 22:52

1 Answers1

4

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)

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182