When you selected NaN for int, why does the value change depending on whether it is assigned to a variable or not?

Bringing double.NaN to int will be 0.

Console.WriteLine(unchecked((int)double.NaN));    // 0

However, assigning the variable double.NaN to a variable, and then casting to int will be -2147483648.

double value = double.NaN;
Console.WriteLine (unchecked ((int) value));    // -2147483648
Console.WriteLine ((int) value);                // -2147483648

Why does the result change depending on whether to assign it to a variable or not?

C # specification

6.2.1 Explicit numerical conversions

  • In the tested context, the conversion is as follows:
    • If the operand value is NaN or infinite, a System.OverflowException is thrown.
    • Otherwise, the source operand is rounded to zero to the nearest integer value. If this integer value is within the destination range, then this value is the result of the conversion.
    • System.OverflowException.
  • .
    • NaN , .
    • . , .
    • .

Envrionment

  • : Visual Studio 2013
  • Rimtime:.NET Framework 4.6.0
  • : Windows 10 Version 1607
  • : Intel Core i7 920

:

Console.WriteLine(Environment.OSVersion);    // Microsoft Windows NT 6.2.9200.0
Console.WriteLine(Environment.Version);      // 4.0.30319.42000
+4
2

unchecked. Thatswhy , , unchecked.

, :

  • .
    • NaN , .

( ).

Unspecified , . 0 -2147483648 - .

, , -2147483648 . .

+3

, , , . 0, NaN. int, Int32 , double. , , :

  • NaN , . .
  • , .

int, "-2147483648", , 32- . , NaN double.NegativeInfinity . double.NegativeInfinity int.MinValue, , .

, , , , . NaN, - , NaN ( , ). NaN . , , .

+1

Source: https://habr.com/ru/post/1671158/


All Articles