I have a double output
which is being printed as -0.000000
我有一个双输出,打印为-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?
这样可以保持打印第三个条件,说-0.000000小于0.为什么这样,我该如何解决这个问题呢?
1 个解决方案
#1
5
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.
发生这种情况是因为内存中的双重表示并不精确。例如,输出可以等于-0.000000000000012,但printf只打印第一个数字。你可以尝试printf(“%。20lf”,输出);打印更多数字。
However, it is not a good practice to use the operator ==
with floating points.
但是,使用带有浮点的operator ==不是一个好习惯。
#1
5
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.
发生这种情况是因为内存中的双重表示并不精确。例如,输出可以等于-0.000000000000012,但printf只打印第一个数字。你可以尝试printf(“%。20lf”,输出);打印更多数字。
However, it is not a good practice to use the operator ==
with floating points.
但是,使用带有浮点的operator ==不是一个好习惯。