I am writing a game loop in Java and trying to calculator deltas. When attempting to get the current time, the following does not give me an error in my IDE. However the function returning a double, where are System.nanoTime() return a long. Why is this not an error?
private static double getTime() {
return System.nanoTime() / 1000000000;
}
Is explicitly casting to a double better?
private static double getTime() {
return (double) System.nanoTime() / (double) 1000000000;
}
答案 0 :(得分:2)
In the first function, the division will be integer division and the result of the division will be casted to double
. It is thus equivalent of return (double)(System.nanoTime() / 1000000000);
So for example if the System.nanoTime()
gives a value of 142154
, the getTime()
will return 0, because in integer division the fractions are ignored. 142154 / 1000000000
returns a value of 0.000142154
which will thus be rounded to zero.
The second function will on the otherhand perform an floating-point division, which will keep the fractions and thus be more precise. You don't have to cast both of the arguments to double
, only one of them.
The reason the first version of getTime()
will not give an error is that Java implicitly casts long
to double
because double
is more precise data type than long
. For the same reason int
can be implicitly casted to long
(but not other way around!).