Possible Duplicate:
print the float value in integer in C language
I am trying out a rather simple code like this:
float a = 1.5;
printf("%d",a);
It prints out 0. However, for other values, like 1.4,1.21, etc, it is printing out a garbage value. Not only for 1.5, for 1.25, 1.5, 1.75, 1.3125 (in other words, decimal numbers which can be perfectly converted into binary form), it is printing 0. What is the reason behind this? I found a similar post here, and the first answer looks like an awesome answer, but I couldn’t discern it. Can any body explain why is this happening? What has endian-ness got to do with t?
you’re not casting the float,
printfis just interpreting it as an integer which is why you’re getting seemingly garbage values.Edit:
Check this example C code, which shows how a
doubleis stored in memory:If you run that with
1.5it printsIf you try it with 1.41 it prints
So when
printfinterprets1.5as an int, it prints zero because the 4 LSBs are zeros and some other value when trying with1.41.That being said, it is an undefined behaviour and you should avoid it plus you won’t always get the same result it depends on the machine and how the arguments are passed.
Note: the bytes are reversed because this is compiled on a little indian machine which means the least significant byte comes first.