-2

I have the below C code.

int main (void)
{
    printf("%d\n",5/(float)4.7);
    printf("Size of int = %d",sizeof(int));
    return(1);
}

But the result is 1610612736 I was expecting the result to be 1 since we are tying to print an integer. Why this is the case? How float value is getting converted to a large value in printf statement? I am using codeblock + mingw

Jon Wheelock
  • 263
  • 3
  • 16
  • 3
    What is going on? Is it 'Bad Specifier Day' or something? – Martin James Feb 23 '16 at 15:43
  • Please use a language with strong typing, e.g. Python. – too honest for this site Feb 23 '16 at 15:45
  • @MartinJames Today is `%d`-day. – Lundin Feb 23 '16 at 15:57
  • @MartinJames the question is not a duplicate. The OP didn't realize that `5/(float)4.7` leads to a float value. But he wants to print an integer (and correctly has `%d` format specifier). – Paolo Feb 23 '16 at 15:57
  • [What happens when I use the wrong format specifier?](http://stackoverflow.com/q/16864552/995714), [What can happen if printf is called with a wrong format string?](http://stackoverflow.com/q/14504148/995714) – phuclv Feb 23 '16 at 16:08
  • The `printf("Size of int = %d",sizeof(int));` also has a mismatch between the format specifier and the type of the value it corresponds to. It should be `printf("Size of int = %zd",sizeof(int));` or `printf("Size of int = %d",(int)sizeof(int));`, although it would be better to use `printf("Size of int = %zu",sizeof(int));` or `printf("Size of int = %u",(unsigned int)sizeof(int));`. – Ian Abbott Feb 23 '16 at 18:00

1 Answers1

4

as you're trying to print an integer you have to cast the result to int

printf("%d\n",(int)(5/(float)4.7));

otherwise 5/(float)4.7 is a float

You see 1610612736 because the float value is "interpreted" as and int leading to and odd result.

Paolo
  • 15,233
  • 27
  • 70
  • 91