問題描述
我有代碼來計算兩個數字之間的百分比差異 - (oldNum - newNum)/oldNum * 100;
- 其中兩個數字都是 double
s.我希望在 oldNum 為 0 的情況下必須添加某種檢查/異常處理.但是,當我對 oldNum 和 newNum 的值都為 0.0 進行測試運行時,執行繼續進行,就好像什么都沒發生并且沒有引發錯誤一樣.使用 int
s 運行此代碼肯定會導致算術除零異常.為什么Java在涉及到double
s時會忽略它?
I have code to calculate the percentage difference between 2 numbers - (oldNum - newNum) / oldNum * 100;
- where both of the numbers are double
s. 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 int
s would definitely cause an arithmetic division-by-zero exception. Why does Java ignore it when it comes to double
s?
推薦答案
除以零的結果在數學上是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時不拋出異常?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!