java - 除以 0.0 的核心 Java

标签 java string arithmeticexception

我听说过 Java 中的一个转折点。如果有人知道正确的原因,您会被要求分享。 问题是:

double result1 = 1.0/0.0;
sop(result1); // output Infinity
double result2 = 0.0/0.0;
sop(result2); // output NaN

float 变量也是如此。但对于 int 类型,它会引发 ArithmeticException。为什么?

注意:我使用的是jdk 1.7

最佳答案

您不能使用 int 表示无穷大或 NAN。

来自 JLS

The result of a floating-point division is determined by the rules of IEEE 754 arithmetic:

Division of a nonzero finite value by a zero results in a signed infinity. The sign is determined by the rule stated above.

检查 IEEE explanation

Why doesn't division by zero (or overflow, or underflow) stop the program or trigger an error? Why does a standard on numbers include "not-a-number" (NaN)? The 754 model encourages robust programs. It is intended not only for numerical analysts but also for spreadsheet users, database systems, or even coffee pots. The propagation rules for NaNs and infinities allow inconsequential exceptions to vanish. Similarly, gradual underflow maintains error properties over a precision's range.

When exceptional situations need attention, they can be examined immediately via traps or at a convenient time via status flags. Traps can be used to stop a program, but unrecoverable situations are extremely rare. Simply stopping a program is not an option for embedded systems or network agents. More often, traps log diagnostic information or substitute valid results.

Flags offer both predictable control flow and speed. Their use requires the programmer be aware of exceptional conditions, but flag stickiness allows programmers to delay handling exceptional conditions until necessary.

关于java - 除以 0.0 的核心 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29370369/

相关文章:

java - 如何使用parseInt将字符串转换为整数?

java - 为什么它暗示我要除以零?

java - 我正在尝试使用 jsp 和 servlet 从我的 psql 数据库中使用复选框来删除条目

java - 从两个自定义对象列表中删除公共(public)元素

java - 在 Java If Else block 中将多个变量连接到一个字符串

c++ - 在这种情况下如何从结构中输入字符串数组?

使用 sprintf() 将文本复制到字符数组中 - C/Atmel studio 7

java - 如何在android中获取文件数组的大小?

java MonetaryConversions 为高位货币抛出 ArithmeticException

c# - 克隆 Git 存储库抛出 ArithmeticException