14

I've seen this finance calculation code at my friend's computer :

double Total = ...
double Paid = ...
double Wating_For_Details = ...
double Decuctibles = ...
double Rejected = ...

Well , the moment I saw this , I told him that double is represented at base 2 and can NOT represent finance calculation. use decimal instead.

great.

But the moment I change it to double Ive encountered :

Attempted to divide by zero.

HUH ?

Apparently - using double , when dividing with 0.0 it does NOT throws exception :

enter image description here

But returns NAN.

While my code (using decimal) does throw exception ( when Total is zero)

And so I ask :

I checked 0.0==0 and it returns true. so why I'm not getting exception but NAN? I know thats how it should be but where is the common sence of not throwing exception when dividing double by zero ?

4

5 回答 5

17

与整数类型的操作不同,在溢出或非法操作(例如被零除)的情况下会引发异常,浮点值的操作不会引发异常。相反,在特殊情况下,浮点运算的结果是零、正无穷大、负无穷大或不是数字 (NaN):

DoubleMSDN 上

于 2013-07-04T14:43:50.520 回答
8

请参阅http://msdn.microsoft.com/en-us/library/system.double.nan.aspx

当操作的结果未定义时,方法或运算符返回 NaN。例如,零除以零的结果是 NaN,如下例所示。(...) 此外,使用 NaN 值的方法调用或对 NaN 值的操作会返回 NaN,如下例所示。

以下代码示例说明了 NaN 的使用:

  Double zero = 0;

  // This condition will return false. 
  if ((0 / zero) == Double.NaN) 
     Console.WriteLine("0 / 0 can be tested with Double.NaN.");
  else 
     Console.WriteLine("0 / 0 cannot be tested with Double.NaN; use Double.IsNaN() instead.");
于 2013-07-04T14:45:18.500 回答
3

当除以零 (0.0) 时,double 有一些特殊行为:

d/0.0 => Double.NaN if d==0.0
d/0.0 => Double.PositiveInfinity if d>0.0
d/0.0 => Double.NegativeInfinity if d<0.0

DivideByZeroException 仅针对 Integer 抛出(Decimal 就像!)

于 2013-07-04T14:46:44.197 回答
1

http://msdn.microsoft.com/en-us/library/6a71f45d%28VS.80%29.aspx

浮点算术溢出或除以零永远不会引发异常,因为浮点类型基于 IEEE 754,因此具有表示无穷大和 NaN(非数字)的规定。

这个答案提供了一些很好的背景

于 2013-07-04T14:44:44.890 回答
1

这是记录在案的:

当操作的结果未定义时,方法或运算符返回 NaN。例如,零除以零的结果是 NaN。

于 2013-07-04T14:44:00.613 回答