0

Can you tell why this statement in C gives 0 as output

printf("Hello %f",-5/2);

Whereas

printf("Hello %d",-5/2);

is giving output as -2

dbush
  • 186,650
  • 20
  • 189
  • 240

1 Answers1

12

Division of two integers produces a integer result (int in this case). The %f format specifier expects an argument of type double. Using the wrong format specifier for a given argument triggers undefined behavior which in this case gives you an incorrect result.

If you want a floating point result, at least one of the operands to / must have a floating point type, i.e.

printf("Hello %f",-5.0/2);
dbush
  • 186,650
  • 20
  • 189
  • 240