java 为什么整数除以零 1/0 给出错误但浮点 1/0.0 返回“Inf”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5291606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:27:22  来源:igfitidea点击:

Why does integer division by zero 1/0 give error but floating point 1/0.0 returns "Inf"?

javadoubleint

提问by Fábio Perez

I'm just curious about this:

我只是对这个很好奇:

When evaluating 1/0in Java, the following exception occurs:

1/0在 Java 中求值时,发生以下异常:

Exception in thread "main" java.lang.ArithmeticException: / by zero at Foo.main(Foo.java:3)

线程“main”中的异常 java.lang.ArithmeticException: / 在 Foo.main(Foo.java:3) 处为零

But 1/0.0is evaluated to Infinity.

1/0.0被评估为Infinity.

public class Foo {
    public static void main (String[] args) {
        System.out.println(1/0.0);
    }
}

Why does this happen?

为什么会发生这种情况?

采纳答案by ninjalj

That's because integers don't have values for +/-Inf, NaN, and don't allow division by 0, while floats do have those special values.

这是因为整数没有 +/-Inf、NaN 的值,并且不允许除以 0,而浮点数确实有这些特殊值。

回答by Kristóf Marussy

1/0 is a division of two ints, and throws an exception because you can't divide by integer zero. However, 0.0 is a literal of type double, and Java will use a floating-point division. The IEEE floating-point specification has special values for dividing by zero (among other thing), one of these is double.Infinity.

1/0 是两个int的除法,并抛出异常,因为您不能除以整数零。但是, 0.0 是double类型的文字,Java 将使用浮点除法。IEEE 浮点规范具有除以零的特殊值(除其他外),其中之一是 double.Infinity。

If you're interested in details, the floating-point spec (which is often cryptic) has a page at Wikipedia: http://en.wikipedia.org/wiki/IEEE_754-2008, and its full text can be also read online: http://ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=4610933.

如果你对细节感兴趣,浮点规范(通常是神秘的)在维基百科有一个页面:http: //en.wikipedia.org/wiki/IEEE_754-2008,它的全文也可以在线阅读:http: //ieeexplore.ieee.org/xpl/mostRecentIssue.jsp?punumber=4610933

回答by Erik

1/0 is integer division, 1/0.0 is floating point division - Floats can represent invalid values, integers can't.

1/0 是整数除法,1/0.0 是浮点除法 - 浮点数可以表示无效值,整数不能。

回答by Evan Mulawski

The IEEE has defined certain standards for floating point numbers which include definitions for "Not a Number" and positive and negative infinity. These do not apply to integers.

IEEE 为浮点数定义了某些标准,其中包括“非数字”和正无穷大和负无穷大的定义。这些不适用于整数。

See http://steve.hollasch.net/cgindex/coding/ieeefloat.html

http://steve.hollasch.net/cgindex/coding/ieeefloat.html

The reason for these special cases in basically rounding errors. Floating point numbers are often always truncated because they are never exact. Integers, on the other hand, are always exact.

这些特殊情况的原因基本上是四舍五入的错误。浮点数通常总是被截断,因为它们从不准确。另一方面,整数总是精确的。