为什么 printf 打印错误的值? [英] Why does printf print wrong values?
问题描述
当我使用 printf("%f
", myNumber)
打印 int
时,为什么会得到错误的值?
Why do I get the wrong values when I print an int
using printf("%f
", myNumber)
?
我不明白为什么它用 %d
打印得很好,但用 %f
打印不行.不应该只是添加额外的零吗?
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
", a, b, c, d, e); //prints fine
printf("%f %f %f %f %f
", a, b, c, d, e); //prints weird stuff
推荐答案
当然它会打印奇怪"的东西.你传入了 int
s,但告诉 printf
你传入了 float
s.由于这两种数据类型具有不同且不兼容的内部表示,因此您会得到胡言乱语".
well of course it prints the "weird" stuff. You are passing in int
s, but telling printf
you passed in float
s. Since these two data types have different and incompatible internal representations, you will get "gibberish".
当您将变量传递给像 printf
这样的可变参数函数时,没有自动转换",这些值将作为它们实际的数据类型传递到函数中(或升级到更大的兼容类型)某些情况).
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:
union {
int n;
float f;
} x;
x.n = 10;
printf("%f
", x.f); /* pass in the binary representation for 10,
but treat that same bit pattern as a float,
even though they are incompatible */
这篇关于为什么 printf 打印错误的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!