Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
724 views
in Technique[技术] by (71.8m points)

c - Strange output when comparing same float values?

Comparing Same Float Values In C

strange output in comparison of float with float literal

Float addition promoted to double?


I read the above links on floating points, but even getting strange output.

#include<stdio.h>
int main()
{
    float x = 0.5;

    if (x == 0.5)
        printf("IF");

    else if (x == 0.5f)
        printf("ELSE IF");

    else
        printf("ELSE");
}

Now, according to the promotion rules, Shouldn't "ELSE IF" must be printed ?

But, here it is printing "IF"


EDIT : Is it because 0.5 = 0.1 in binary and everything is 0 after that and loss of precision hence no effects, so comparison IF returns true.

Had it been 0.1, 0.2, 0.3, 0.4, 0.6, 0.7.... , then Else If block returns true.


Pardon me asking same question, because I have read from the above links that floats comparison must never be done.

But, What is the reason of this unexpected behaviour ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As you have read the links regarding problems with floating point types and comparisons, you are probably expecting that 0.5 is rounded during conversion and hence the comparison should fail. But 0.5 is a power of 2 and can be represented perfectly without any rounding in a float or double type variable. Therefore the comparison results in TRUE.

After your edited your question: Yes, if you took 0.1 or one of the other values you mention, you should run into the else part.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...