-2

I am seeing anomalous behavior in print function while dealing with int and float numbers.

float y = 9/5;
printf("%f", y);

printf("%f", 9/5);

First print statement outputs 1.000000 which is acceptable while other outputs 0.000000. Why outputs are different in both cases?

Anurag
  • 37
  • 1
  • 6

1 Answers1

8

9/5 is an integer and it's value is 1.

printf("%f", 9/5); is undefined behaviour because %f expects a double but you provide an int.

Try printf("%f", 9.0/5); and the output will be what you expect.

More generally spoken: if the format specifiers of printf don't match the arguments, the behaviour is undefined; in most cases you get unexpected output.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115