对于这个代码块:
int num = 5;
int denom = 7;
double d = num / denom;
d
的值为 0.0
。可以通过强制转换强制工作:
double d = ((double) num) / denom;
但是还有其他方法可以获得正确的 double
结果吗?我不喜欢转换原语,谁知道会发生什么。
最佳答案
double num = 5;
这避免了类型转换。但是您会发现 Actor 转换是明确定义的。您不必猜测,只需检查 JLS . int 到 double 是一个扩大的转换。来自 §5.1.2 :
Widening primitive conversions do not lose information about the overall magnitude of a numeric value.
[...]
Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision-that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode (§4.2.4).
5 可以精确地表示为 double 。
关于java - 整数除法 : How do you produce a double?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3144610/