float to int unexpected behaviour

前端 未结 6 832
情话喂你
情话喂你 2020-11-30 16:05

can you please explain the o/p behavior of this program.

int main()
{
  float a = 12.5;
  printf(\"%d\\n\", a);
  printf(\"%d\\n\", *(int *)&a);
  return         


        
6条回答
  •  长情又很酷
    2020-11-30 16:30

    Let's see.

    1. Floats are stored in a format defined in IEEE 754. See here: http://en.wikipedia.org/wiki/IEEE_754-2008
    2. Side note: You're passing a double into a float in your first instruction. This will be cast at compile-time, but some compilers might complain. If you mean to use a float, append an f: float a = 12.5f;
    3. You're passing a float into a %d argument. That is not good. Compilers may behave differently here, some might warn you about it. If you want to pass in a float, use %f.
    4. You're taking the IEEE-754-formatted integer and printing it out. See the link in item 1 to see what you're printing.

提交回复
热议问题