[英]Floating-point division - bias to avoid a result less than an 'exact' value
[英]Floating point value of 0 greater than 0
我不能用一个简单的程序重现这个,但在我的程序的某个地方我有类似的东西:
float e = f(...);
if (e > 0.0f) {
...
printf("%f", e)
表示e
为0.000000
,但e > 0.0f
为真......所以e > 0
且e > 0.0
。 我错过了什么?
浮点值大于零,但小于1e-7。 这是印刷问题。 使用科学记数法printf(“%e”,值); 或“%g”表示最短表示法。
printf("%f", e)
显示为零的事实并不意味着什么,因为printf
将值四舍五入到十进制浮点和输出的精度,因此非常小的数字可能大于0被推出为0。
尝试printf("%e", e)
或printf("%.17f", e)
,看看会发生什么。
问题是浮点值大于0,但小于printf用于打印%f
浮点数的精度。 您可以使用%e
或%g
获得更好的结果,如以下程序所示。
#include <math.h>
#include <stdio.h>
void main(void)
{
int i;
float e;
for (i = 1; i < 64; i++) {
printf("Decimal places: %d\n", i);
e = 1.0 / pow(10, i);
if (e > 0.0f) {
printf("Value displayed with %%e: %e > 0.0f\n", e);
printf("Value displayed with %%f: %f > 0.0f\n", e);
printf("Value displayed with %%g: %g > 0.0f\n\n", e);
}
}
}
您需要使用数学库编译它 。 对于gcc使用: -lm
你的问题是e
实际上不是零。 它有一些微小的值,但它被隐藏,因为%f
转换为十进制,失去精度。 使用printf("%e",e)
作为调试语句,您将看到其中存在非零值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.