0
#include<stdio.h>
#include<math.h>
int main()
{

printf("%f",3/2);
printf(" %d",3/2);
printf(" %d",3<<2);
return 0;

}

Here is my code, i was expecting to get 1.50000 1 12

but i received 2.168831 1 12

as my output.

  • Integer division results in integers and it truncates the fractional part. This is written down in every reasonably good beginner C tutorial, and at least a hundred answers here on Stack Overflow. Do some research. –  Oct 20 '13 at 09:42
  • Hi, thanks for the reply, im fairly new here sorry about that tried searching for it but was unable to. Also if you could give me a break down on how it works......because in my head it goes (int)3/2 = (int)1 and then float value should be 1.000000 –  Oct 20 '13 at 09:45
  • 1
    What leads you to believe it **should** be 1.000? `printf()` is not magic. It knows exactly **nothing** about the types of the expressions you pass it (that's why you have to use a format string). It's not magic. But read the accepted answer to the duplicate and you will know. –  Oct 20 '13 at 09:54
  • please correct me if im wrong but is the value displayed a garbage value or does it have some significance ? –  Oct 20 '13 at 09:55
  • 2
    It has no significance because of undefined behavior. **Read the answer of the linked question already.** –  Oct 20 '13 at 09:55
  • See the answer to this [question](http://stackoverflow.com/questions/8223740/how-printf-function-handle-f-specification). 2.168831 is what happens to be in the xmm0 register at the moment you call printf. Given the number of results when you google for 2.168831, I'd say it has some significance. But its significance is not linked to your code. – damienfrancois Oct 20 '13 at 10:25

1 Answers1

5

You get a mixture of mis-converted bytes (the integer you passed) & transient data off the stack, formatted as a floating-point number. @H2CO3 gave a good reference.

This is because you are passing an int, but you have told printf() to expect a floating-point value (specifically, a double). If you use %f as a format, you need to pass a double. Failure to do so causes undefined & erroneous access to undefined/ garbage values on the stack.

Both operands integers 3 / 2 will perform an integer division. Make one or both the operands doubles, ie 3.0 / 2, and you'll have floating-point division & printf() will function as you expect.

Thomas W
  • 13,940
  • 4
  • 58
  • 76