3

我不能用一个简单的程序来重现这个,但是在我的程序的某个地方我有类似的东西:

float e = f(...);
if (e > 0.0f) {
    ...

printf("%f", e)表明e0.000000, 但e > 0.0f是 真的 ...... 也是e > 0e > 0.0。我错过了什么?

4

4 回答 4

6

The floating point value is larger than zero, but less than 1e-7. It's printing issue. Use scientific notation printf("%e", value); or "%g" for shortest notation.

于 2012-11-14T11:51:25.107 回答
3

The fact that printf("%f", e) shows it to be zero doesn't mean anything, because printf rounds the value both to decimal floating point and to the precision of the output, so very small numbers larger than 0 are likely to be put out as 0.

Try printf("%e", e) or printf("%.17f", e) and see what happens.

于 2012-11-14T11:51:48.150 回答
3

问题是浮点值大于 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

于 2012-11-14T12:08:00.500 回答
0

你的问题是e实际上不是零。它有一些微小的价值,但由于%f转换为十进制而被隐藏起来,失去了精度。改为用作您的调试语句,您将printf("%e",e)看到其中有一个非零值。

于 2012-11-14T11:54:40.623 回答