给出了以下代码:
long testNum = 1000;
double midNum = testNum/60000;
System.out.println(midNum);
long another = Math.round(7600/midNum);
System.out.println(another);产出如下:
0.0
92233720368547758070.0?如何在java中获得正确的结果?0,为什么下一个表达式有一个结果?它不应该抛出一个by zero表达式吗?发布于 2015-02-04 15:19:24
为什么第一个输出是0.0?
您正在使用整数除法,所以这是正确的结果。
如何在java中获得正确的结果?
不要使用整数除法,而是使用浮点数,这是使值之一成为浮点的最简单方法。
double midNum = testNum/60000.0;或
double midNum = testNum/60e3;既然第一个输出是0,为什么下一个表达式有一个结果?
浮点算法在浮点中使用IEEE-754标准(有时称为IEEE-753.99999999999998 ;),在Java中永远不会得到异常,您可能得到无穷大、负无穷大或NaN。
整数没有无限,也没有NaN,无法表示这一点,所以它产生了一个异常。
当你把任何对long来说太大的数字舍入时,它给出了最近的可表示值,即Long.MAX_VALUE。
顺便说一句
long l = Math.round(Double.POSITIVE_INFINITY); // l == Long.MAX_VALUE
long l = Math.round(Double.NEGATIVE_INFINITY); // l == Long.MIN_VALUE
long l = (long) Double.NaN; // l == 0从Double,您可能会发现这很有趣。
public final class Double extends Number implements Comparable<Double> {
/**
* A constant holding the positive infinity of type
* {@code double}. It is equal to the value returned by
* {@code Double.longBitsToDouble(0x7ff0000000000000L)}.
*/
public static final double POSITIVE_INFINITY = 1.0 / 0.0;
/**
* A constant holding the negative infinity of type
* {@code double}. It is equal to the value returned by
* {@code Double.longBitsToDouble(0xfff0000000000000L)}.
*/
public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
/**
* A constant holding a Not-a-Number (NaN) value of type
* {@code double}. It is equivalent to the value returned by
* {@code Double.longBitsToDouble(0x7ff8000000000000L)}.
*/
public static final double NaN = 0.0d / 0.0;
/**
* A constant holding the largest positive finite value of type
* {@code double},
* (2-2<sup>-52</sup>)·2<sup>1023</sup>. It is equal to
* the hexadecimal floating-point literal
* {@code 0x1.fffffffffffffP+1023} and also equal to
* {@code Double.longBitsToDouble(0x7fefffffffffffffL)}.
*/
public static final double MAX_VALUE = 0x1.fffffffffffffP+1023; // 1.7976931348623157e+308发布于 2015-02-04 15:21:37
长是不能保持小数。Long等于int,只是具有较高的范围。
您应该使用十进制或浮点数。
发布于 2015-02-04 15:22:18
您的第一个结果是0.0,原因是您使用了隐式转换。当将一个长除以一个数字时,Java假设这个数字是相同类型的,并且会进行“长”除法,这个除法没有余数。因为1,000/60000介于0到1之间,所以结果实际上是0,当它是双倍时,结果被转换为0.0。您可以通过将一行更改为double midNum = testNum/60000D;来修复此问题。
请注意结尾处的"D“,表示60000是双倍。这将迫使长时间作为一个双重,并给予适当的结果。
对于第二部分,你基本上是除以一个非常小的数字,使它看起来相当大。0.0不能被精确地表示为双,所以实际上是除以略高于0.0的部分,当您修复另一部分时,它将被修复。
https://stackoverflow.com/questions/28324847
复制相似问题