問題描述
Utilities.getDistance(uni, enemyuni) <= uni.getAttackRange()
Utilities.getDistance 返回 double 并且 getAttackRange 返回 int.上面的代碼是 if 語句的一部分,它必須是真的.那么比較有效嗎?
Utilities.getDistance returns double and getAttackRange returns int. The above code is part of an if statement and it needs to be true. So is the comparison valid?
謝謝
推薦答案
是的,它是有效的 - 它會在執行比較之前將 int
提升為 double
.
Yes, it's valid - it will promote the int
to a double
before performing the comparison.
請參閱 JLS 部分 15.20.1(數值比較運算符),鏈接到 JLS 第 5.6.2 節(二進制數字提升).
來自后者:
加寬原語轉換(第 5.1.2 節)適用于轉換以下規則中指定的一個或兩個操作數:
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
如果任一操作數是 double 類型,則另一個操作數將轉換為 double.
If either operand is of type double, the other is converted to double.
...
這篇關于在java中將double與int進行比較是否有效?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!