简体   繁体   English

根据设计,为什么C#编译器允许将任何float或double值除以零?

[英]By design, why does the C# compiler allows any float or double values to be divided by zero?

By design, why does the C# compiler allows any float or double values to be divided by zero? 根据设计,为什么C#编译器允许将任何float或double值除以零?

class Program
{
    static void Main(string[] args)
    {
        double x = 0.0 / 0;

        float y = 1f / 0;


    }
}

Because IEEE 754 floating-point values have special non-numeric values to deal with this: 因为IEEE 754浮点值具有特殊的非数字值来处理这个问题:

PS Home:\> 1.0/0
Infinity
PS Home:\> 0.0/0
NaN

whereas dividing an integer by zero is always an exception (in the C# sense 1 ), so you could just throw the exception directly. 将整数除以零总是一个例外(在C#意义上1 ),所以你可以直接抛出异常。


1 Dividing a floating-point number by zero is also an exception but at a completely different level and many programming languages abstract this away. 1将浮点数除以零也是一个例外,但是处于完全不同的水平,许多编程语言将其抽象出来。

因为浮点值具有无穷大的有效(且真正有用)表示,而任何类型的整数都没有。

The reason the compiler allows you to divide a float or a double by zero, is that float and double have representations on the notion of positive infinity and negative infinity (and "not a number"), so it is a meaningful thing to allow. 编译器允许你将float或double除以零的原因是float和double在正无穷大和负无穷大(和“不是数字”)的概念上有表示,所以允许它是有意义的。

One oddity is that the compiler fails spot 一个奇怪的是编译器失败了

 decimal d = 2; 
 decimal d2 = d/0M

as a divide by zero, even though it does spot it if you write the equivalent code for an integer. 如果你写一个整数的等价代码,即使它确实发现了它,也可以除以零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM