Using printf function

后端 未结 5 830
时光说笑
时光说笑 2021-01-22 13:01

I\'ve never bothered to look for printf as I started learning C++ without C. Now i want to use formatted output in some project. so I\'m looking for some references that can exp

相关标签:
5条回答
  • 2021-01-22 13:07

    It actually invokes undefined behavior (UB). If the format specifier doesn't match with the type of the argument passed to printf, then it is UB, which means anything could happen. It can print 0, or 9878978 or any garbage. Anything, entirely unpredictable, could happen.

    Use %f if the data type of the argument is float.

    0 讨论(0)
  • 2021-01-22 13:15

    if you don't want to use %d format specifier ,then you better Type cast it Explicitly to avoid UB(Undefined Behavior ) to be called.

    float f=1.5; printf("%d",(int)f);

    0 讨论(0)
  • 2021-01-22 13:21

    Because %d is for printing integers, not floats. You need one of the floating point format strings, like %f.

    The usual conversions between data types don't work here because printf is a varargs-type function where you can basically push whatever you want onto the stack (or equivalent if your implementation is not stack-based) and, if it doesn't match what's in your format string, all bets are off - it's undefined behaviour.

    See here for one of the things that can go wrong when you have such a mismatch.

    0 讨论(0)
  • 2021-01-22 13:28

    When you write printf("%d", f); the type of f must be int. The code as you have written it invokes undefined behaviour. Taken from an answer to a similar question:

    in the documentation for fprintf (7.19.6.1/9) which also applies to printf, it explicitly states that if any argument is not the correct type for the format specifier - for an unmodified %d, that is int - then the behaviour is not defined.


    Why does it print zero?

    Maybe they ran out of nasal demons?

    0 讨论(0)
  • 2021-01-22 13:30

    Yes you already have the answer, %d will print integer values only. Use "%f" which stands for float values . If you use %f you will get 1.500000

    0 讨论(0)
提交回复
热议问题