使用 printf 函数
当我开始学习没有 C 的 C++ 时,我从来没有费心去寻找 printf。现在我想在一些项目中使用格式化输出。所以我正在寻找一些参考资料来解释使用 printf 和 IO 流之间的区别。
我的疑问之一是:
float f = 1.5;
printf("%d", f);
为什么它打印零? FWIK 它应该将 float 重新解释为 int 这是真的吗?
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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
它实际上调用了未定义行为(UB)。如果格式说明符与传递给
printf
的参数的类型不匹配,那么它就是 UB,这意味着任何事情都可能发生。它可以打印0
、9878978
或任何垃圾。任何完全不可预测的事情都可能发生。如果参数的数据类型为
float
,请使用%f
。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 print0
, or9878978
or any garbage. Anything, entirely unpredictable, could happen.Use
%f
if the data type of the argument isfloat
.当您编写
printf("%d", f);
时,f
的类型必须是 int。您编写的代码会调用未定义的行为。摘自类似问题的答案:也许他们用完了鼻恶魔?
When you write
printf("%d", f);
the type off
must be int. The code as you have written it invokes undefined behaviour. Taken from an answer to a similar question:Maybe they ran out of nasal demons?
因为
%d
用于打印整数,而不是浮点数。您需要浮点格式字符串之一,例如%f
。数据类型之间的常见转换在这里不起作用,因为 printf 是一个可变参数类型函数,您基本上可以将您想要的任何内容推送到堆栈上(或者如果您的实现不是基于堆栈的,则等效)并且,如果它与格式字符串中的内容不匹配,则所有赌注都将关闭 - 这是未定义的行为。
请参阅此处 对于当你有这样的不匹配时可能出错的事情之一。
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.
是的,您已经有了答案,
%d
将仅打印整数值。使用“%f
”代表浮点值。如果您使用%f
您将得到1.500000
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 get1.500000
如果你不想使用 %d 格式说明符,那么你最好显式地对其进行类型转换,以避免调用 UB(未定义行为)。
浮动 f=1.5;
printf(“%d”,(int)f);
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);