java - 整数除法 : How do you produce a double?

标签 java casting integer-division

对于这个代码块:

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/

相关文章:

java - 编写一个程序,提示用户输入两点(包括工作)

java - ObjectMapper 从具有特定名称的字段创建列表

scala - 转换 "hollow"更高种类的类型值以避免实例化

64-bit - 如何将 128 位被除数除以 64 位除数,其中被除数的位均为 1,而我只需要商的 64 LSB?

c# - 如何检查一个整数是否是给定整数的总和?

java - 整数除法 : Why is the result of 1/3 == 0?

java - 是否可以为注入(inject)的 Java 资源设置 Lifestyle

java - 向 Android 应用程序添加依赖项后出错

C++ - 字节数组到值的平台独立函数,反之亦然

c++ - 需要帮助以避免沮丧