C#中的0.0/0.0不会抛出“试图除以零". [英] 0.0/0.0 in C# won't throw "Attempted to divide by zero."?

查看:55
本文介绍了C#中的0.0/0.0不会抛出“试图除以零".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在朋友的计算机上看到了此财务计算代码:

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

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

好吧,当我看到这一点时,我告诉他 double 表示为 base 2 ,并且可以 NOT 表示财务计算.改用 decimal .

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.

太好了.

但是当我将其更改为Ive的两倍时,遇到了

But the moment I change it to double Ive encountered :

试图除以零.

嗯?

显然-使用 double ,除以 0.0 时,它确实会引发异常:

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

但返回 NAN .

虽然我的代码(使用十进制)确实引发了异常(当 Total zero 时)

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

所以我问:

我检查了 0.0 == 0 并返回true.那为什么我没有得到异常,而是 NAN ?我知道应该是这样,但是在将double除以零时不抛出异常的常识在哪里呢?

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 ?

推荐答案

请参见

当操作的结果不确定时,方法或操作符将返回NaN.例如,将零除以零的结果为NaN,如以下示例所示.(...)另外,使用NaN值的方法调用或对NaN值进行的操作将返回NaN,如以下示例所示.

A method or operator returns NaN when the result of an operation is undefined. For example, the result of dividing zero by zero is NaN, as the following example shows. (...) In addition, a method call with a NaN value or an operation on a NaN value returns NaN, as the following example shows.

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

The following code example illustrates the use of 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.");

这篇关于C#中的0.0/0.0不会抛出“试图除以零".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆