floating point - Adding float values in c -
why f 0.0 after adding 0.1?
#include <stdio.h> int main() { float f=0.0f; f = f + 0.1f; printf("f %f \n",&f); return 0; }
sorry messed original question
why these 2 values not ? because of precision. sorry have ask question here because i'm blocked can't ask more questions
#include <stdio.h> int main() { float f=0.0f; int i; for(i=0;i<10;i++) {f = f + 0.1f; } if(f == 1.0f) printf("f 1.0 \n"); else printf("f %f not 1.0\n",f); return 0; }
printf("f %f \n",f);
gives correct output. see here-https://ideone.com/158zbv
to print address printf(" %p \n",&f);
.
where printf
statement give undefined behaviour.
about second code - can re-write if
condition -
if(f>0.99f && f<1.01f)
so gives correct output- https://ideone.com/karx3a
edit
while adding in program value of f
not 1.0f
may have different value ,when see value more decimal places bit different 1.0f
that's why code go else part .
see here value f
has every iteration-https://ideone.com/wj7u1r
Comments
Post a Comment