简体   繁体   中英

Float to integer rounding too early(?)

I'm not entirely sure if the title is accurate, because I don't know the real issue. Basically, I'm making trying to render a fuel element into my game, but I'd like it to fit its container of 98 pixels. What I've already done is the following:

    float fuelDisplay = fuel / maxFuel;
    float fuelDisplayFinal = fuelDisplay*98;
    g.setColor(Color.YELLOW);
    g.fillRect(15, 81, (int)fuelDisplayFinal, 38);
    g.drawImage(Bank.bar, 0, 70, null);

When I start the game, it looks fine, but as soon as the variable 'fuel' is decreased, the bar disappears completely (most likely has its width set to 0).

Now, I'm assuming that as soon as it's cast to an integer, it simply rounds down to zero, but I'm not sure how to work around this. I couldn't find a solution anywhere, and similar problems that I've found have been 'resolved' by doing precisely what I've done. Any and all help is appreciated. This could just be a case of me being very ignorant, but I hope not. Thanks everyone!

If both fuel and maxFuel are integers, the result of fuel / maxFuel will be an integer before you try to assign it to fuelDisplay .

So, if fuel == 99 and maxFuel == 100 , the result of the integer division will be zero, and so will fuelDisplay despite being a float itself.

You can get around this by using floats for your variables or (probably better) casting to ensure the result is floating point:

float fuelDisplay = (float) fuel / maxFuel;

Alternatively, you can get rid of floating point altogether by rearranging your formulae:

int fuelDisplayFinal = fuel * 98 / maxFuel;
g.setColor(Color.YELLOW);
g.fillRect(15, 81, fuelDisplayFinal, 38);
g.drawImage(Bank.bar, 0, 70, null);

assuming that fuelDisplay is only used locally here and that you never need the fuelDisplayFinal in floating point form later on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM