# Thread: Floating Values acting weird.

1. ## Floating Values acting weird.

Code:
```#include<stdio.h>
#include<conio.h>
void main()
{
float x=0.1;
if(x==0.1)
printf("If");
else
printf("Else");
getch();
}```
I have tried values 0.1,0.2,0.3,0.35,0.3000025. None seem to print the word "If", they print "Else".

Could somebody help me with the reason for the same.

2. 0.1 can be stored internally as 0.099999
or 0.100001 for example

you can never be sure...

so if you really need to compare floats do something like
Code:
`if(abs(x-y)<delta)`
where delta is small enough for considering to float numbers as the same

3. Vart i do agree with the part of 0.1 being stored that way, but why is it so and even if it is so. If it stores 0.1 as 0.099999 or 0.1000001 then why does it not compare it also that way?

4. The problems began with void main.

Then this happened - http://c-faq.com/fp/strangefp.html

5. 'cause in the statement x == 0.1
x is a float and 0.1 is double
so they can be stored as 0.999999 and 0.999999999999999
then both converted to double will give different values...

for example...
as I said - you never know how the float value is stored internally

6. > if(x==0.1)
Because the left hand side is a float, and the right hand side is a double, and in the float to double conversion, you get a slightly different approx of 0.1, one which is different.

if ( x == 0.1f )
Might just work, but as stated, you should never compare floats for equality.

7. Code:
```else
printf("%f,x");
getch();
}```
If i do this it returns the value of x as 0.100000.

As per ur link salem, i understand that the processor's registers and the memory store values differently. So is there no way perfect way for equating floats?

Vart do u mean to say that the rvalue of the if statement is by default a "double"?

8. a constant is by default a double

9. > So is there no way perfect way for equating floats?
Floats and doubles are always approximations.

Find the David Goldberg, ``What Every Computer Scientist Should Know about Floating-Point Arithmetic''

10. Thx guys u actually genuinely solved a query which i was banging my head for, I am from India and we have teachers with bookish knowledge so wouldnt expect an answer from them.

Popular pages Recent additions