将 double 传递给 Graphics fillRect 方法

Passing a double to Graphics fillRect method

我正在使用 Java AWT。

我需要在 g.fillrect() 中使用 double,但此函数只需要一个 int。问题是我需要 double。如果我有一个 int 比 java 除法将它变成零。我该如何解决这个问题?

g.fillRect(e.getX(), e.getY(), (double)(e.getWidth() * (e.getHealth() / e.getMaxHealth())), 5);

(int)(e.getWidth() * (double)(e.getHealth() / e.getMaxHealth()))
这样 getHealth()/getMaxHealth() 的结果将是一个双精度数,当且仅当 getWidth()*(the-result-fraction) 大于 1 时,这将使整个结果大于零。

您也可以使用 ceil() 如果这样会得到想要的结果:
Math.ceil(e.getWidth() * (double)(e.getHealth() / e.getMaxHealth()));

不要将可视化健康栏的大小与健康字段的大小混淆。假设健康是一个从 0 到 4 的整数。可视化条的大小应该是:

// MAX_HEALTH is a constant, value 4
// maxWidthHealthBar is an int that is the maximal size of the displayed
// healthBar
// healthBarWidth is the length of the colored portion of the health bar
int healthBarWidth = (health * maxWidthHealthBar) / MAX_HEALTH;

先做乘法再做除法,你的整型除法应该没问题。