0

Having such simple C++ instructions:

int f1 = 3238;

printf_s("Printf_1.cpp 1 - float: %d\n", f1);
printf_s("Printf_1.cpp 2 - float: %f\n", f1);

The output of the second printf_s is 0.000000 My question is why there isn't just 3238.000000? What happened with 3238 integral part of the number?

PS. My specs: Win 10, Microsoft Visual Studio Community 2019

Daros911
  • 435
  • 5
  • 14
  • 4
    You are lying to printf about the type of argument. Undefined Behaviour follows. – Yksisarvinen May 12 '21 at 08:59
  • dupe of [Why does printf("%f",0); give undefined behavior?](https://stackoverflow.com/questions/38597274/why-does-printff-0-give-undefined-behavior) et al. – underscore_d May 12 '21 at 09:10

1 Answers1

1

printf requires variable argument types to match your format specifiers. In particular, %f expects you to pass double, and you pass int. printf interprets bytes of your int in that way so it prints out 0.000000, but in general there is no warranty what such combination should produce (and that's called "Undefined Behavior"). What you need to do is add explicit typecast to double: printf("%f", (double) f1).

ivan.ukr
  • 2,853
  • 1
  • 23
  • 41