开发者

Using printf function

I've never b开发者_运维问答othered 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 explain the difference between using printf and IO streams.

One of my doubt are:

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

Why does it print zero? FWIK it should be reinterpreting float as int is that true?


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.


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?


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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜