本文介绍了整数除法:如何产生双精度数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于这个代码块:

int num = 5;
int denom = 7;
double d = num / denom;

d 的值为 0.0.它可以通过强制转换来强制工作:

the value of d is 0.0. It can be forced to work by casting:

double d = ((double) num) / denom;

但是还有其他方法可以获得正确的 double 结果吗?我不喜欢强制转换原语,谁知道会发生什么.

But is there another way to get the correct double result? I don't like casting primitives, who knows what may happen.

推荐答案

double num = 5;

这避免了演员表.但是您会发现强制转换是明确定义的.您不必猜测,只需查看 JLS.int 到 double 是一种扩大转换.来自 §5.1.2:

That avoids a cast. But you'll find that the cast conversions are well-defined. You don't have to guess, just check the JLS. int to double is a widening conversion. From §5.1.2:

扩展原始转换不会丢失有关整体的信息数值的大小.

[...]

int 或 long 值的转换浮动,或长期价值双倍,可能会导致损失精度——即结果可能会丢失一些最低有效位价值.在这种情况下,结果浮点值将是一个正确四舍五入的版本整数值,使用 IEEE 754舍入到最近模式 (§4.2.4).

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 可以精确地表示为双精度数.

5 can be expressed exactly as a double.

这篇关于整数除法:如何产生双精度数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 10:11
查看更多