If you are not checking the condition correctly

Asked

Viewed 108 times

1

I was trying to make a very basic little program to know if a variable had a second decimal place or not. However I came across a "bug", which in my view is bizarre.

Code:

#include <stdio.h>
#include <math.h>

int main(void) {
    float f = 1.10;
    float truncado = (f - trunc(f)) * 10;
    printf("Truncado: %f\n", truncado);
    float mod = fmodf(truncado, 1.0f);
    printf("Mod: %f\n", mod);
    if (mod != 0){
        printf("%.2f", f);
    }
    else{
        printf("%.1f", f);
    }
    return 0;
}

Output:

Truncado: 1.000000
Mod: 0.000000
1.10

If the program is pointing out that the variable mod is equal to zero because it is giving true in the if?

See on Ideone.

2 answers

4

First, if returns nothing, it just decides what to do based on the expression contained in it.

Floating point number does not provide accuracy, then its equality occurs in some cases, but not in the majority. That’s just one of the reasons why you can’t use it for monetary value.

No palliative solution is good. What you can do is normalize, IE, treat as if it were a fixed point making conversion to integer according to the desired scale.

  • 1

    Exact, as suggested, the correct is to use your IF in this way: if ((int)mod != 0), with this, you will get the expected result.

4


Let’s do the following: show plus decimal places of the mod and see if he really is 0.0.

For that, I’ll use the library <float.h> and change your printf. The edition is arranged here: https://ideone.com/fR3MV0

Note that your float is not 0.0.

To solve this, you can:

  • parse the float for int and make a normal comparison or;
  • work at intervals, such as considering 0.0 if the number is in a range: -0.00001 < x < 0.00001

EDIT:

Ah, and the problem of mod not exactly equal to 0.0 has nothing to do with your code. It has to do with the shape that the float is stored in the memory, being a power of 2, with whole exponent and mantissa. But this is already beyond the scope of the question.

Anyway, I hope it helps you somehow.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.