Int vs Double and divide by zero exception [duplic

2019-02-18 06:38发布

This question already has an answer here:

We get compile time error when integer is divided by zero whereas in case of double there is no compilation error but at run-time we get infinity/NaN as the result. Any idea why int & double have different behavior when it comes to divide by zero exception?

void Main()
{
    int number = 20;
    var result1 = number/0; // Divide by zero compile time exception

    double doubleNumber = 20;
    var result2 = doubleNumber/0.0; // no compile time error. Result is infinity or NaN
}

3条回答
女痞
2楼-- · 2019-02-18 06:57

Because that's how it's defined. Whereas with integers there are no special values for infinity and NaN, so the compiler throws an error if it can spot the problem at compile time.

查看更多
The star\"
3楼-- · 2019-02-18 07:12

theoretically speaking division by zero should result in infinity, but the integer datatype has nothing to represent infinity. the double datatype does, so there is no need to throw an exception there.

查看更多
倾城 Initia
4楼-- · 2019-02-18 07:18

Because of their mathematical background. Infinity is defined for floating point numbers but not for integers.

查看更多
登录 后发表回答