为什么不将双数除以零会引发异常? [英] Why doesn't dividing by zero with doubles throw an exception?

查看:106
本文介绍了为什么不将双数除以零会引发异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码:

class Program
{
    static void Main(string[] args)
    {
        double varrr = Divide(10, 0);
    }

    static double Divide(double a, double b)
    {
        double c = 0;
        try
        {
            c = a / b;
            return c;
        }
        catch (DivideByZeroException)
        {
            Console.WriteLine("Division by zero not allowed");
            return 0;
        }
    }

}

我曾经期望被零除会抛出 DivideByZeroException ,但是没有,当我在控制台上打印结果时,输出为 Infinity。为什么?

I was expecting division by zero to throw a DivideByZeroException but it did not, and when I print the result on the console the output is "Infinity". Why is that?

推荐答案

原因很简单: DivideByZeroException 不适用于浮点数。

The reason is simple: DivideByZeroException is not designed for floating point numbers.

根据 MSDN


试图将整数或十进制值除以零时抛出的异常。

The exception that is thrown when there is an attempt to divide an integral or Decimal value by zero.

因此,它不是用于浮点值的。根据 IEEE 754 ,浮点数例外包括:

So it's not for floating point values, though. According to IEEE 754, floating point number exceptions include:



  • 除以零(对有限操作数进行的运算会给出确切的无限结果,例如1/0或log(0))(默认情况下返回±无穷大

  • Division by zero (an operation on finite operands gives an exact infinite result, e.g., 1/0 or log(0)) (returns ±infinity by default)

如果您确实需要此代码希望看到异常:

You want this code if you really want to see the exception:

static double Divide(int a, int b)
{
    int c = 0;
    try
    {
        c = a / b;
        return c;
    }
    catch (DivideByZeroException)
    {
        Console.WriteLine("Division by zero not allowed");
        return 0;
    }
}

这篇关于为什么不将双数除以零会引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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