I'm trying to compare 2 float variables.
But comparison failed because of different sign:
int main()
{
//---------------------------------
float d = 0.1;
float f1, f2;
printf("data: %.1f\n", d);
//---------------------------------
d -= 0.1; // 0.0
f1 = d;
printf("data: %.1f\n", d);
printf("f1: %.1f\n", f1);
//---------------------------------
d -= 0.1; // -0.1
printf("data: %.1f\n", d);
//--------------------------------
d += 0.1; // -0.0
f2 = d;
printf("data: %.1f\n", d);
printf("f2: %.1f\n", f2);
//---------------------------------
if (f1 == f2)
{
printf("f1 and f2 equals\n"); // should get here
}
else
{
printf("f1 and f2 NOT equals\n");
}
if (f2 != -0.0)
{
printf("f2 NOT equal -0.0 \n"); // should get here
}
else
{
printf("f2 equals -0.0 \n");
}
}
Output: output
- data: 0.1
- data: 0.0
- f1: 0.0
- data: -0.1
- data: -0.0
- f2: -0.0
- f1 and f2 NOT equals
- f2 NOT equal -0.0
How can I properly set conditions to compare -0.0 and 0.0 values?