简体   繁体   中英

Floating point value of 0 greater than 0

I can't reproduce this with a simple program, but somewhere in my program I have something like:

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

printf("%f", e) shows that e is 0.000000 , yet e > 0.0f is true... So is e > 0 and e > 0.0 . What am I missing?

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.

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.

The problem is that the floating point value is greater than 0, but less than the precision that printf uses to print floating point numbers with %f . You can use %e or %g for better results as illustrated with the following program.

#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);

    }
  }
}

You will need to compile this with the maths library . For gcc use: -lm

Your problem is that e is actually not zero. It has some tiny value in it, but that gets hidden because %f converts to decimal, losing precision. Use printf("%e",e) instead as your debug statement, and you will see that there is a nonzero value in there.

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