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;

这避免了强制转换。但您会发现强制类型转换是明确定义的。你不必猜测,只需检查 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/56603382/

相关文章:

java - int 除以 int 得到 BigDecimal

java - 如何在 Android 中为对象制作动画?

java - 如何通过maven编译classes排除注解

java - JavaFX Standalone JAR 能否获得对 Main java 类的 javascript 引用?

java - YES_NO_OPTION JOptionPane 继续 'yes' 上的 java 代码

java - 将什么传递给 Arrays 实例方法 toArray(T[] a) 方法?

xcode - 在 Swift 中将字符串转换为 double 值 (Xcode v 7.0.1)

java - 将子对象强制转换为不同的 Java 子对象

c - 整数除法的行为是什么?

Python 2.7 - 连分数扩展 - 理解错误