问题
Why C# allows:
1.0 / 0 // Infinity
And doesn't allow:
1 / 0 // Division by constant zero [Compile time error]
Mathematically, is there any differences between integral and floating-point numbers in dividing by zero?
回答1:
According to Microsoft, "Floating-point arithmetic overflow or division by zero never throws an exception, because floating-point types are based on IEEE 754 and so have provisions for representing infinity and NaN (Not a Number)."
回答2:
Mathematically, there is no difference. With computers, however, only the standard IEEE-754 floating-point specification has special values for representing ±∞. Integers can only hold... integers :-)
回答3:
The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is the most widely-used standard for floating-point computation, and is followed by many hardware and software implementations, including the C# compiler.
This means that a floating-point variable in C# can contain a bit pattern that represents strange creatures such as PositiveInfinity, NegativeInfinity, and Not-a-Number (abbreviated as NaN). Under the IEEE 754 arithmetic rules, any of these non-finite floating-point values can be generated by certain operations. For example, an invalid floating-point operation such as dividing zero by zero results in NaN.
In your specific examples, you can see that C# (unlike VB) overloads the / operator to mean either integer or floating-point division, depending on the numeric types of the numbers involved.
In the first example the compiler sees 1.0, and therefore uses floating-point division and puts the result into a floating-point variable. That variable contains a representation of infinity.
In the second example the compiler sees 1, and therefore uses integer division and puts the result into an integer variable. Because integral types in C# use two's complement system for representation, and don't use any special bit patterns to represent infinity (or NaN), the compiler gives an error.
There are also other interesting floating-point subtleties. And it's worth reading Eric Lippert's blog entry on the subject.
回答4:
Floating point division is govered by IEEE754, which specifies that divide by zero should be infinity. There is no such standard for integer division, so they simply went with the standard rules of math.
来源:https://stackoverflow.com/questions/4262286/why-does-c-sharp-allow-dividing-a-non-zero-number-by-zero-in-floating-point-type