在 C 中使用 sizeof 运算符为浮点数据类型 (5.0) 分配 8 个字节而不是 4 个字节
float data type(5.0) being assigned 8 bytes rather that 4 using sizeof operator in C
为什么 sizeof(5.0)
return 8 作为其输出而不是 4,因为我的机器为 float
数据类型分配了 4 个字节?
默认情况下是否将 5.0
视为 double
(分配的内存 = 8 字节),如果是,那么为什么会这样?
因为所有浮点字面量默认为double
。如果您希望它成为 float
,则使用 f
后缀,如 5.0f
.
阅读例如this floating point constant (literal) reference 获取更多信息。
是的。
N1570(最新的 C11 草案),§6.4.4.2 p4:
An unsuffixed floating constant has type double
. If suffixed by the letter f
or F
, it has
type float
. If suffixed by the letter l
or L
, it has type long double
.
至于你的“为什么”问题,在实践中,float
由于其精度非常有限而很少有用,所以这个默认值 "makes sense"。如果您没有充分的理由(例如非常有限的内存限制),请根本不要使用 float
。如果你真的需要一个float
常量,写5.0f
.
为什么 sizeof(5.0)
return 8 作为其输出而不是 4,因为我的机器为 float
数据类型分配了 4 个字节?
默认情况下是否将 5.0
视为 double
(分配的内存 = 8 字节),如果是,那么为什么会这样?
因为所有浮点字面量默认为double
。如果您希望它成为 float
,则使用 f
后缀,如 5.0f
.
阅读例如this floating point constant (literal) reference 获取更多信息。
是的。
N1570(最新的 C11 草案),§6.4.4.2 p4:
An unsuffixed floating constant has type
double
. If suffixed by the letterf
orF
, it has typefloat
. If suffixed by the letterl
orL
, it has typelong double
.
至于你的“为什么”问题,在实践中,float
由于其精度非常有限而很少有用,所以这个默认值 "makes sense"。如果您没有充分的理由(例如非常有限的内存限制),请根本不要使用 float
。如果你真的需要一个float
常量,写5.0f
.