简体   繁体   中英

negative double zero not equal to zero?

I have a double output which is being printed as -0.000000

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM