Why (int)double.NaN and (int)double.PositiveInfinity are 0?

前端 未结 2 2127
栀梦
栀梦 2021-01-03 22:22

in C#, if you 0/0 you get an exception.

But if you 0.0/0 or 0.0/0.0 you get double.NaN and

相关标签:
2条回答
  • 2021-01-03 22:36

    It depends on what kind of context you're in. If you use a checked context, you'll get an exception. The relevant section of the spec is section 6.2.1:

    For a conversion from float or double to an integral type, the processing depends on the overflow checking context (§7.6.12) in which the conversion takes place:

    • In a checked context, the conversion proceeds as follows:
      • If the value of the operand is NaN or infinite, a System.OverflowException is thrown.
      • Otherwise, the source operand is rounded towards zero to the nearest integral value. If this integral value is within the range of the destination type then this value is the result of the conversion.
      • Otherwise, a System.OverflowException is thrown.
    • In an unchecked context, the conversion always succeeds, and proceeds as follows.
      • If the value of the operand is NaN or infinite, the result of the conversion is an unspecified value of the destination type.
      • Otherwise, the source operand is rounded towards zero to the nearest integral value. If this integral value is within the range of the destination type then this value is the result of the conversion.
      • Otherwise, the result of the conversion is an unspecified value of the destination type.

    So in an unchecked context, the answer isn't necessarily 0 - it's an unspecified int value. In fact, in my testing, it comes up as int.MinValue rather than 0 in an unchecked context.

    But fundamentally, if you want to do checking, use a checked context (at least for that expression).

    0 讨论(0)
  • 2021-01-03 22:55

    This is mainly due to the fact that double.NAN and double.PositiveInfity ( or double.Negative for the matter) are not numbers but rather values to identify a concept.

    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.

    try this to illustrate that concept.

    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.");
    
    0 讨论(0)
提交回复
热议问题