Home > Blockchain >  How to test float value in c?
How to test float value in c?

Time:10-13

I want to test if float value is equal to 0.00 or 0.0 and I wanted to know how to correctly test my variables so please correct me if I'm wrong :

int main()
{
    float x1 = -105.00;
    float x2 = 7.00;
    float x3 = 2.00;
    if((x1 == 0.0f || x1 == 0.0))
    {
        if((x2 == 0.0f || x2 == 0.0))
        {
            if((x3 == 0.0f || x3 == 0.0))
            {
                printf("full null\r\n");
            }
        }
    }
}

So I wanted to know if it is the best way to test float in c.

CodePudding user response:

To test whether a float x is zero, use x == 0.f. This will evaluate to 1 if and only if the value of x is zero. (Due to C’s various automatic conversions, x == 0. and x == 0 will have the same effect.)

If x is a floating-point number derived from previous calculations that may have rounding errors, then x may be non-zero even though the “ideal” result1 would be zero or vice-versa. In this case, whether it is possible to use x to make a decision about the real result depends on circumstances. For example, if x is farther away from zero than the rounding errors could possibly account for, then the ideal result cannot be zero either. However, if x is close to zero, then it may be impossible to determine from x whether the ideal result is zero or not.

Footnote

1 By “ideal” result, I mean the result of performing the same calculations using real-number arithmetic with no rounding errors, instead of floating-point arithmetic.

CodePudding user response:

For this specific example, i.e. comparing if all floats are zero, all you need is

int main()
{
    float x1 = -105.00;
    float x2 = 7.00;
    float x3 = 2.00;
    if (x1 == 0 && x2 == 0 && x3 == 0)
    {
        printf("full null\r\n");
    }
}

No magic, no strange things happening, just plain compares.

  • Related