+2

C - Comparing a float

Consider this snippet of code: //float y = 0.1; float y = 1.0; if(y == 1.0){ printf("equal"); } else { printf("NOT equal"); } Why if I assign y = 0.1 and compare with 0.1 is "NOT equal, whilst if I assign y = 1.0 and compare with 1.0 is "equal"?

1/25/2020 7:29:18 PM

Paolo De Nictolis

3 Answers

New Answer

+6

It's because y is a float and a usual floating point number is stored as double. If you'd use double y instead you won't notice the issue. You could also write y == 0.1f to explicitly declare 0.1 to be a float. The reason behind this: 1.0 is stored as just zeros both in floats and doubles (the bit for the 1 is left out in order to store more numbers within floats and doubles). Other numbers however differ in their representation as float or double.

+5

Try assigning numbers as a float by doing 0.1f when you do just 0.1 it's a double

+2

It is a Boolean == as true or false or in your code equal or NOT equal .01 == 1.0 //false or NOT equal 1.0 == 1.0 //true or equal https://docs.microsoft.com/en-us/cpp/cpp/equality-operators-equal-equal-and-exclpt-equal?view=vs-2019