2013-04-06 124 views
0

我用Java數學有問題。我有以下表現:用浮點數和雙精度計算的

double tripp = (timeNow-previousTime)/(seconds*Sys.getTimerResolution())*trip; 

當我試圖計算我的立方體的旋轉速度。這裏是我的完整的代碼功能,我這樣做:

public float getTripLenghtToGo(int seconds, double trip) { 
    long timeNow = Sys.getTime(); 
    System.out.println("RES: "+Sys.getTimerResolution()); 
    double tripp = (timeNow-previousTime)/(seconds*Sys.getTimerResolution())*trip; 
    System.out.println("("+timeNow+"-"+previousTime+")/("+seconds+"*"+Sys.getTimerResolution()+")*"+trip+" = "+tripp); 
    if(tripp != 0){ 
     previousTime = timeNow; 
    } 
    return (float)tripp; 
} 

我使用OpenGL所以它必須返回浮動。它返回浮點數,但始終爲零。

+0

你能提供你的調試輸出語句的輸出嗎? – flyx 2013-04-06 17:09:29

回答

2

timeNowlong類型。你部門的「上層」部分給予了很長時間。整個部門將會很長。你需要把它加倍,否則小數部分會丟失。

例如,輸出:

long timeNow = 10; 
long previousTime = 1; 
double trip = 0.1d; 
int seconds = 50; 

double trippCast = ((double) (timeNow-previousTime))/((double)seconds)*trip; 
System.out.println(trippCast); 
double trippWithoutCast = (timeNow-previousTime)/seconds*trip; 
System.out.println(trippWithoutCast); 

是:

0.018 
0.0 
0

兩種可能性:

  • 使用System.nanoTime() - 它爲您提供了更精確的時間測量
  • 使用((double)(timeNow-previousTime))/(seconds*Sys.getTimerResolution()) - 如果你劃分一個lo ng和int,結果會很長。這就是0L