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/40196295/

相关文章:

android - 在 Java 中,如何将 Realm 对象转换为我希望写入数据库的类?

template-meta-programming - 通过乘法生成一个查找表来除以 10 位整数

整数除法余数的 C++ 确定性

performance - 快速硬件整数除法

java - 在 Java 中获取输入的最有效方法是什么?

java - hibernate JPA : how to write an efficent persist()?

c++ - 将 QString 转换为 char* 不稳定?

java - 从另一个 Activity 获取textView的文本

java - 重新分配 JList 和 JComboBox 数据

vb.net - 您可以将 "type"作为参数传递吗?