使用双精度数的正确表示法
在java中,在带或不带“.0”的双精度运算中编写常量在风格上更可接受?
如,
double var= 200.0; 双 d= var/250.0; 双 h= 1.0 - d;
相比
与double var= 200 ; 双 d= var/250; 双 h= 1 - d;
谢谢
It is more stylistically acceptable in java to write constants in double operations with or without ".0" ?
As in,
double var= 200.0;
double d= var/250.0;
double h= 1.0 - d;
vs.
double var= 200;
double d= var/250;
double h= 1 - d;
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这与风格本身无关。当您编写
double var = 200;
时,200
是 整型文字 然后通过 扩大原始转换。最好具体一点 - 如果您使用双精度常数,请将其写为双精度:
以上所有内容都是 浮点文字。在第二个示例中,具体化尤为重要:
我故意省略了
var
的类型。目前尚不清楚d
将包含什么结果 - 它可能是0.2
或0.0
(如果var
是整数)。另一方面,如果您编写double d = var / 250.0
,结果将始终为0.2
。It's not about style per se. When you write
double var = 200;
,200
is an integer literal which is then converted into double via widening primitive conversion.It's much better to be specific - if you're using a double constant, write it as double:
All of the above are floating point literals. Being specific is especially important in your second example:
I've omitted the type of
var
on purpose. It's unclear whatd
will contain as a result - it could either be0.2
or0.0
(ifvar
were integer). On the other hand, if you were to writedouble d = var / 250.0
the result would always be0.2
.根据需要前导和尾随零,单精度常量标记为:
0.0
(对于双精度)。0.0f
表示浮点数。Leading and trailing zeros as needed, with single precision constants tagged as such:
0.0
for a double.0.0f
for a float.我不是 Java 爱好者,而是 C 和 C 爱好者。 C++也有同样的问题。对我来说,我总是使用“.0”,这样我就不会被不需要的整数除法所困扰。它还消除了偶尔出现的有关类型转换的编译器警告(尽管由于从整数到浮点的明确定义的类型提升语义,这些警告很少见)。
I'm not a Java guy but C & C++ have the same issue. For me, I always use the ".0" just so that I'm never bitten by unwanted integer division. It also silences the occasional compiler warning about type conversion (though those are rare due to well-defined type promotion semantics from integers to floating point).
大多数人在看到混合类型的算术表达式时要么会“再看一遍”,要么会完全误解它。对于前导零也是如此(在较小程度上);例如
0.1
与.1
。良好的风格就是编写代码,使其易于理解,并且易于其他人维护。因此,使用正确类型的文字而不是依赖提升,并且(在较小程度上)使用前导零是一种很好的风格。
Most people will either do a "double take" when they see an arithmetic expression with mixed types, or completely misunderstand it. The same goes (to a lesser extent) for leading zeros; e.g. in
0.1
versus.1
.Good style is all about writing your code so that it is easy to understand, and easy for some else to maintain. So it follows that it is good style to use literals of the right type, rather than relying on promotion, and (to a lesser extent) to use leading zeros.
正如其他人指出的那样,这只是一个偏好和可读性的问题。请参阅以下代码和反汇编的字节码:
结果:
如您所见,这两种方法几乎完全相同。
As others have pointed out, it is just a question of preference and readability. See the following code and the disassembled bytecode:
result:
As you can see, the two methods are as close to identical as you can get.
.0 更好
it's better with .0