为什么 sizeof(13.33) 是 8 个字节?
当我给出 sizeof(a)
时,其中 a=13.33
是一个浮点变量,大小为 4 个字节。 但如果我直接给出 sizeof(13.33)
,大小就是 8 个字节。
我不明白发生了什么事。有人可以帮忙吗?
When I give sizeof(a)
, where a=13.33
, a float variable, the size is 4 bytes.
But if i give sizeof(13.33)
directly, the size is 8 bytes.
I do not understand what is happening. Can someone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这些是语言的规则。
13.33 是一个数字文字。它被视为双精度,因为它是双精度。如果您希望将 13.33 视为浮点文字,则指定 13.33f。
13.33 是一个双精度字面值。如果 sizeof(float) == 4,则 sizeof(13.33f) == 4 也应该成立,因为 13.33f 是浮点文字。
Those are the rules of the language.
13.33 is a numeric literal. It is treated as a double because it is a double. If you want 13.33 to be treated as a float literal, then you state 13.33f.
13.33 is a double literal. If sizeof(float) == 4, sizeof(13.33f) == 4 should also hold because 13.33f is a float literal.
文字 13.33 被视为双精度浮点值,8 字节宽。
The literal 13.33 is treated as a double precision floating point value, 8 bytes wide.
13.33 文字被视为“双精度”,而不是“浮点型”。
请尝试使用 13.33f。
The 13.33 literal is being treated as 'double', not 'float'.
Try 13.33f instead.
变量的类型和大小都很好。 只是编译器有一些默认的文字类型,这些常量值硬编码在程序中。
如果您请求
sizeof(1)
,您将获得sizeof(int)
。如果您请求sizeof(2.5)
,您将得到sizeof(double)
。这些显然分别适合 char 和 float,但编译器对您的文字有默认类型,并且会在分配之前将它们视为此类。不过,您可以覆盖此默认行为。例如:
干杯!
The type and size of your variable are fine. It's just that the compiler has some default types for literals, those constant values hard-coded in your program.
If you request
sizeof(1)
, you'll getsizeof(int)
. If you requestsizeof(2.5)
, you'll getsizeof(double)
. Those would clearly fit into a char and a float respectively, but the compiler has default types for your literals and will treat them as such until assignment.You can override this default behaviour, though. For example:
Cheers!
因为
13.33
是一个double
,如果您对其进行赋值,它会被截断为float
。double
是 8 个字节。要创建真正的浮点数,请使用13.33f
(注意f
)。Because
13.33
is adouble
, which gets truncated to afloat
if you assign it. And adouble
is 8bytes. To create a real float, use13.33f
(note thef
).