请问这个方案的工作? [英] How does this program work?
问题描述
#include <stdio.h>
int main() {
float a = 1234.5f;
printf("%d\n", a);
return 0;
}
它显示一个 0
!这怎么可能?什么是道理?
It displays a 0
!! How is that possible? What is the reasoning?
我特意放了%d个
在的printf
语句学习的printf
。
I have deliberately put a %d
in the printf
statement to study the behaviour of printf
.
推荐答案
这是因为%d个
预计的 INT
但您提供一个float。
That's because %d
expects an int
but you've provided a float.
使用%E
/ %F
/ %G
打印浮动。
Use %e
/%f
/%g
to print the float.
在为什么打印0:浮点数发送给的printf
之前转换成双击
。在小尾数双重新presentation数1234.5为
On why 0 is printed: The floating point number is converted to double
before sending to printf
. The number 1234.5 in double representation in little endian is
00 00 00 00 00 4A 93 40
A %d个
消耗了32位整数,所以零被打印出来。 (作为一个测试,你可以的printf(%D,%d个\\ N,1234.5f);
你可以得到输出 0,1083394560
)
A %d
consumes a 32-bit integer, so a zero is printed. (As a test, you could printf("%d, %d\n", 1234.5f);
You could get on output 0, 1083394560
.)
至于为什么浮动
转换为双击
,如printf的原型是 INT的printf(为const char *,...)
,从6.5.2.2/7,
As for why the float
is converted to double
, as the prototype of printf is int printf(const char*, ...)
, from 6.5.2.2/7,
在一个函数原型声明符引起的参数类型转换到最后声明参数后,停止省略号。 默认参数提升是在尾随参数执行。
The ellipsis notation in a function prototype declarator causes argument type conversion to stop after the last declared parameter. The default argument promotions are performed on trailing arguments.
和来自6.5.2.2/6,
and from 6.5.2.2/6,
如果它表示所调用的函数的前pression有一个类型不包括样机,整数促销活动每个参数执行,和参数具有类型浮动
都提升到双击
。这些被称为的默认参数提升的
If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type
float
are promoted todouble
. These are called the default argument promotions.
(感谢阿洛克寻找这一点。)
(Thanks Alok for finding this out.)
这篇关于请问这个方案的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!