2017-07-03 29 views
0

對於我的GDX程序,我製作了一個帶有兩個按鈕的選項菜單。其中一個增加了音量,其中一個降低了音量。每按一次按鈕,它就會增加/減少0.1。下面是代碼:Java float unlogical output

soundMButton = new ImageButton(drawableSoundM); 
soundMButton.addListener(new ClickListener(){ 
    @Override 
    public void clicked(InputEvent event, float x, float y) { 
     if (Constants.soundLevel > 0.0) { 
      Constants.soundLevel -= 0.1; 
      System.out.println(Constants.soundLevel); 
     } 
     click.play(1.0f * Constants.soundLevel); 
    } 
}); 

soundPButton = new ImageButton(drawableSoundP); 
soundPButton.addListener(new ClickListener(){ 
    @Override 
    public void clicked(InputEvent event, float x, float y) { 
     if (Constants.soundLevel < 1.0) { 
      Constants.soundLevel += 0.1; 
      System.out.println(Constants.soundLevel); 
     } 
     click.play(1.0f * Constants.soundLevel); 
    } 
}); 

然而,我的輸出

0.9 
0.79999995 
0.6999999 
0.5999999 
0.4999999 
0.39999992 
0.29999992 
0.19999993 
0.09999993 
-7.301569E-8 

有誰知道爲什麼是這樣的,而不是0.9,0.8,0.7,等等?

回答

1

浮球和雙打遭受精度錯誤。你應該將它舍入到1個十進制值。 From Here

DecimalFormat oneDigit = new DecimalFormat("#,##0.0"); 

... 

Constants.soundLevel = Double.valueOf(oneDigit.format(Constants.soundLevel));