C printf 使用 %d 和 %f [英] C printf using %d and %f
问题描述
我正在研究这个程序,我注意到使用 %f 表示 double 和 %d 表示浮点数给了我完全不同的东西.有人知道为什么会这样吗?
I was working on this program and I noticed that using %f for a double and %d for a float gives me something completely different. Anybody knows why this happens?
int main ()
{
float a = 1F;
double b = 1;
printf("float =%d
double= %f", a, b);
}
这是输出
float = -1610612736
double = 190359837192766135921612671364749893774625551025007120912096639276776057269784974988808792093423962875123204096.0000
推荐答案
由于可变参数的工作方式,除了 %d
之外,C 不知道你实际传递的值的类型和 %f
.当你传入一个可变参数时,你基本上是在做 (void*)&myvalue
因为编译器和运行时的函数都不能确定变量的类型,除了在格式化字符串.因此,即使有可用的隐式转换,编译器也不知道需要它.
Because of the way variable parameters work, C has no idea of the type of value you are actually passing it other than %d
and %f
. When you pass in a variable parameter you are basically doing (void*)&myvalue
because neither the compiler, nor the function at run time can determine the type of the variable except for what is given in the formatting string. So even though there is an implicit conversion available, the compiler does not know it is needed.
好吧,在大多数系统上,double 是 8 个字节,而 float 是 4 个字节.所以这两种类型不是二进制兼容的.这就像试图将字符串解释为双精度型或其他一些不兼容的类型.
Well, double is 8 bytes on most systems while float is 4 bytes. So the two types are not binary compatible as it is. And it is like trying to interpret a string as a double, or some other incompatible type.
这篇关于C printf 使用 %d 和 %f的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!