C++ 0 和 0.0 之间的差异
C++中0和0.0有区别吗?您应该使用哪个来初始化双精度?
谢谢
Is there a difference between 0 and 0.0 in C++? Which should you use for initializing a double?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
文字
0
被认为是int
文字;文字0.0
是double
文字。分配给double
时,要么可以工作(因为int
可以以扩大的转换施放);但是,将0.0
施放到int
是一个缩小的转换,必须明确完成;即(int)0.0
。A literal
0
is considered to be anint
literal; literal0.0
is adouble
literal. When assigning to adouble
, either will work (since theint
can be cast in a widening conversion); however, casting0.0
to anint
is a narrowing conversion, and must be done explicitly; i.e.(int)0.0
.我试图保持常数类型一致。 0 for ints。 0.0F或0.F浮子,双重0.0。
对我来说,这样做的最重要原因是编译器和程序员看到同样的事情。
如果我这样做...
...应该分配0或.5?如果我这样做是毫不犹豫的...
I try to keep my constants type-consistent. 0 for ints. 0.0f or 0.f for float, and 0.0 for double.
To me, the most important reason to do this is so the compiler and the programmer see the same thing.
If I do this...
...should r be assigned 0 or .5? There's no hesitation if I do this instead...
一个似乎是整数文字,另一个是浮点字面的。对于编译器而言,无论您是用整数文字初始化浮子还是加倍,都无关紧要。无论如何,文字将被汇编成某些内部表示形式。
我倾向于提出0.0的建议,以使您的意图(对其他程序员)明确清楚。
One appears to be an integer literal, the other a floating point literal. It really doesn't matter to the compiler whether you initialize floats or doubles with integer literals. In any event the literal will be compiled into some internal representation.
I would tend to suggest 0.0 in order to make your intention (to other programmers) explicitly clear.
这是视觉-C ++拆卸:
拆卸
它们产生相同的组件。 Visual-C ++使用XMM寄存器的方法与XMM寄存器。如果您首先加载整数0,然后将其移至XMM寄存器中,它将使用额外的说明。鉴于我们关于如何将
0.0
的假设加载为文字,以及额外的无用指令加载加载整数0,然后将其移至浮点寄存器中尽管这确实没关系,因为编译器作者我们必须假设这种优化已经很长时间了,因为这很明显。如果需要100%的可移植性,那么编写手动使用XOR技术的内联函数更便宜。Here is the Visual-C++ disassembly for:
Disassembly
They produced the same assembly. Visual-C++ uses the method of XOR-ing the XMM register with it'self. Had you first loaded the integer 0 then moved it into the XMM register it would have used an extra instruction. Given our hypothesis on how the
0.0
may be loaded as a literal, as well as the extra useless instruction load loading an integer 0 then moving it into a floating-point register, neither is optimal so it seems as though it really doesn't matter because the compiler writer we must assume this optimization has been know for a long time because it is kind of obvious. If 100% portability is required, then it is more portable to write an inline function that manually uses the XOR technique.