Why doesn#39;t Java throw an Exception when dividing by 0.0?(为什么Java除以0.0时不抛出异常?)
问题描述
我有代码来计算两个数字之间的百分比差异 - (oldNum - newNum)/oldNum * 100; - 其中两个数字都是 doubles.我希望在 oldNum 为 0 的情况下必须添加某种检查/异常处理.但是,当我对 oldNum 和 newNum 的值都为 0.0 进行测试运行时,执行继续进行,就好像什么都没发生并且没有引发错误一样.使用 ints 运行此代码肯定会导致算术除零异常.为什么Java在涉及到doubles时会忽略它?
I have code to calculate the percentage difference between 2 numbers - (oldNum - newNum) / oldNum * 100; - where both of the numbers are doubles. I expected to have to add some sort of checking / exception handling in case oldNum is 0. However, when I did a test run with values of 0.0 for both oldNum and newNum, execution continued as if nothing had happened and no error was thrown. Running this code with ints would definitely cause an arithmetic division-by-zero exception. Why does Java ignore it when it comes to doubles?
推荐答案
除以零的结果在数学上是undefined,可以用float/double表示(如NaN - 不是一个数字),但它在任何基本意义上都没有错.
The result of division by zero is, mathematically speaking, undefined, which can be expressed with a float/double (as NaN - not a number), it isn't, however, wrong in any fundamental sense.
由于整数必须包含特定的数值,因此在处理它们时必须在除以零时引发错误.
As an integer must hold a specific numerical value, an error must be thrown on division by zero when dealing with them.
这篇关于为什么Java除以0.0时不抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么Java除以0.0时不抛出异常?
基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
