 # Why I'm getting different output by only changing the value of variable?

1. int main(){
``````float a=1.25;

if(a==1.25)
printf("abc");
``````

else
{
printf(“xyz”);
}

return 0;
}

output1= abc

1. int main(){
``````float a=0.1;

if(a==0.1)
printf("abc");
``````

else
{
printf(“xyz”);
}

return 0;
}

output2= xyz

This happens because the binary representation of floating point numbers depends on numbers after the decimal point so some numbers do not have exact binary representation which will be required for comparisons.

for further knowledge you can read about standards related to floating point numbers in computation.
And for just this problem’s sake you can use ‘f’ as a suffix to denote a floating point number.

2 Likes

Float equality dont work properly. Instead, we find the absolute difference between two float values and find whether it is less than 10^-9. If yes then they are equal.

E.g.

float a=0.1;
if(abs(a-0.1)<1e-9) printf(“abc”);
else printf(“xyz”);

will print abc

1 Like