Proper notation using doubles
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= va开发者_JAVA技巧r/250.0; double h= 1.0 - d;
vs.
double var= 200; double d= var/250; double h= 1 - d;
Thanks
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:
double d = 200.0;
double another = .01;
double exp = 1E3;
All of the above are floating point literals. Being specific is especially important in your second example:
var = 50;
double d = var / 250;
I've omitted the type of var
on purpose. It's unclear what d
will contain as a result - it could either be 0.2
or 0.0
(if var
were integer). On the other hand, if you were to write double d = var / 250.0
the result would always be 0.2
.
Leading and trailing zeros as needed, with single precision constants tagged as such:
0.0
for a double.
0.0f
for a float.
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).
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:
public class Twohundred {
public void intVersion() {
double d = 200;
}
public void dblVersion() {
double d = 200.0;
}
}
result:
public class Twohundred extends java.lang.Object{
public void intVersion();
Code:
0: ldc2_w #2; //double 200.0d
3: dstore_1
4: return
public void dblVersion();
Code:
0: ldc2_w #2; //double 200.0d
3: dstore_1
4: return
}
As you can see, the two methods are as close to identical as you can get.
it's better with .0
精彩评论