Jake Jake - 3 months ago 39
C Question

negative double zero not equal to zero?

I have a double

which is being printed as

I have a loop that says:

if (output == 0) {
printf("Continuing to go STRAIGHT.\n");
else if (output > 0) {
printf("Turning LEFT.\n");
else if (output < 0) {
printf("Turning RIGHT.\n");

This keeps printing the 3rd condition, saying that -0.000000 is less than 0. Why is this and how can I correct the issue?


This happen because the double representation in memory is not exact. For example, output can be equal to -0.000000000000012, but printf only print the firsts digits. You can try printf("%.20lf", output); to print more digits.

However, it is not a good practice to use the operator == with floating points.