为什么 printf 打印错误的值?
使用 printf("%f\n", myNumber)
打印 int
时,为什么会得到错误的值?
我不明白为什么它用 %d
打印得很好,但用 %f
却不行。难道不应该只是添加额外的零吗?
int a = 1;
int b = 10;
int c = 100;
int d = 1000;
int e = 10000;
printf("%d %d %d %d %d\n", a, b, c, d, e); //prints fine
printf("%f %f %f %f %f\n", a, b, c, d, e); //prints weird stuff
Why do I get the wrong values when I print an int
using printf("%f\n", myNumber)
?
I don't understand why it prints fine with %d
, but not with %f
. Shouldn't it just add extra zeros?
int a = 1;
int b = 10;
int c = 100;
int d = 1000;
int e = 10000;
printf("%d %d %d %d %d\n", a, b, c, d, e); //prints fine
printf("%f %f %f %f %f\n", a, b, c, d, e); //prints weird stuff
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
当然,它会打印“奇怪”的东西。您传递的是 int,但告诉 printf 您传递的是 float。由于这两种数据类型具有不同且不兼容的内部表示,因此您将得到“乱码”。
当您将变量传递给像 printf 这样的变量函数时,没有“自动转换”,值将作为它们实际的数据类型传递到函数中(或者在某些情况下升级为更大的兼容类型) 。
您所做的与此有些相似:
well of course it prints the "weird" stuff. You are passing in
int
s, but tellingprintf
you passed infloat
s. Since these two data types have different and incompatible internal representations, you will get "gibberish".There is no "automatic cast" when you pass variables to a variandic function like
printf
, the values are passed into the function as the datatype they actually are (or upgraded to a larger compatible type in some cases).What you have done is somewhat similar to this:
如果要将它们打印为浮点数,可以在将它们传递给 printf 函数之前将它们转换为浮点数。
If you want to print them as floats, you can cast them as float before passing them to the printf function.
a、b、c、d 和 e 不是浮点数。 printf() 将它们解释为浮点数,这会在屏幕上打印奇怪的内容。
a, b, c, d and e aren't floats. printf() is interpreting them as floats, and this would print weird stuff to your screen.
在
printf()
中使用不正确的格式说明符会调用未定义行为
例如:
注意:
printf()
中double
的格式说明符代码> 是<代码>%f。Using incorrect format specifier in
printf()
invokesUndefined Behaviour
For example:
Note: format specifier for
double
inprintf()
is%f
.问题是……在
printf
内部。发生以下情况the problem is... inside
printf
. the following happensprintf 和变量参数的工作方式是字符串中的格式说明符,例如“%f %f”,告诉 printf 类型以及参数的大小。通过为参数指定错误的类型,它会变得混乱。
查看 stdarg.h 以了解用于处理变量参数的宏
the way printf and variable arguments work is that the format specifier in the string e.g. "%f %f" tells the printf the type and thus the size of the argument. By specifying the wrong type for the argument it gets confused.
look at stdarg.h for the macros used to handle variable arguments
对于“正常”(具有指定所有类型的非可变参数函数),编译器会在需要时将整数值类型转换为浮点类型。
对于可变参数,这种情况不会发生,它们总是“按原样”传递。
For "normal" (non variadac functions with all the types specified) the compiler converts integer valued types to floating point types where needed.
That does not happen with variadac arguments, which are always passed "as is".