gpt4 book ai didi

Java float 非逻辑输出

转载 作者:行者123 更新时间:2023-12-02 12:42:32 28 4
gpt4 key购买 nike

对于我的 GDX 程序,我制作了一个带有两个按钮的选项菜单。其中之一增加音量,其中之一降低音量。每当单击按钮时,它就会增加/减少 0.1。这是代码:

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 等?

最佳答案

float 和 double 会出现精度错误。您应该将其四舍五入为 1 位小数。 From Here .

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

...

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

关于Java float 非逻辑输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44882170/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com