First off, you should never be using ==
or !=
with floating point variables. They are essentially meaningless operations, as the limitations of floating point types mean that even seemingly innocuous values might not compare identically. It is completely possible that 2 + 2 isn't 4, at least as far as ==
would identify it.
The real issue here is that you are making use of the sign of a "zero" value, which as per above, might not actually be exactly zero in the first place, but more importantly, is difficult to test for using standard comparison operators. See this related question for some discussion.
The best solution for this, if you have access to C++11 or a compiler supporting it, is to use copysign
as per Vlad's answer on that question. This function takes 2 parameters. The first represents the magnitude of the return value, and the second the sign. Here is an example:
#include "iostream"
#include <math.h>
using namespace std;
int main()
{
double posZero = +0.0d;
double negZero = -0.0d;
if( copysign( 1, posZero ) < 0 )
{
cout << "posZero is negative\n";
}
else
{
cout << "posZero is positive\n";
}
if( copysign( 1, negZero ) < 0 )
{
cout << "negZero is negative\n";
}
else
{
cout << "negZero is positive\n";
}
}
posZero is positive
negZero is negative
In this example, copysign
creates a value of +/- 1, according to the sign on the second argument. The first argument for your purposes could be any non-zero value, but might as well be 1.
Alternatively, you could use signbit, which is honestly probably more direct. A version of the above using this function:
#include "iostream"
#include <math.h>
using namespace std;
int main()
{
double posZero = +0.0d;
double negZero = -0.0d;
if( signbit( posZero ) )
{
cout << "posZero is negative\n";
}
else
{
cout << "posZero is positive\n";
}
if( signbit( negZero ) )
{
cout << "negZero is negative\n";
}
else
{
cout << "negZero is positive\n";
}
}
With the same output.