If you are not checking the condition correctly

2

It was me, trying to do a pretty basic program to know if a variable had a second decimal place or not. But 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, why is it giving true in if?

See the Ideone .

    
asked by anonymous 09.07.2017 / 05:14

2 answers

3

Let's do this: show plus decimal places of mod and see if it's even 0.0 .

For this, I'm going to use the <float.h> library and change its printf . The issue is available here: link

Note that your float is not 0.0 .

To solve this, you can:

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

EDIT:

Oh, and the problem of mod not exactly equal to 0.0 does not have to do with your code. It has to do with how float is stored in memory, being a power of 2, with integer exponent and mantissa. But that is beyond the scope of the question.

Anyway, I hope this helps you in some way.

    
09.07.2017 / 06:07
4

First, if does not return anything, it just decides what to do based on the expression contained in it.

Floating-point number does not provide accuracy , so its equality occurs in some cases, but not in most cases . This is just one of the reasons why you can not use it for monetary value.

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

    
09.07.2017 / 05:26