Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
int main( ) { int x = 5; float y = 3.1f; printf("int x=%d ,float x=%f ,y=%f, y=%d\n", x, x, y, y); //X86 return 0; }
我认为答案是 5 、 5.0 、 3.1 、 3。但答案是 在此处输入图像描述
为什么?
%d格式说明符需要一个类型的参数,int并且%f需要一个类型的参数double(可能从 提升float)。如果传递错误类型的参数,则行为未定义。
%d
int
%f
double
float
解决方案:不要那样做。
(最可能的行为是包含int值的内存或寄存器将显示为好像它是 type double,但任何事情都可能发生。)
对于大多数函数调用,将 an 传递int给期望double参数的函数会导致值被转换,因此42变为42.0. 但是由于printf是variadic,预期的类型是由格式字符串决定的,而不是参数类型,所以编译器一般不能知道生成类型转换。
42
42.0
printf