gpt4 book ai didi

c# - 将 NaN 转换为 int 时,为什么值会根据是否分配给变量而变化?

转载 作者:太空狗 更新时间:2023-10-30 01:14:35 29 4
gpt4 key购买 nike

将 double.NaN 转换为 int 将为 0。

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

但是,将 double.NaN 赋给一个变量然后转换为 int 将是 -2147483648。

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

为什么结果会根据是否分配给变量而改变?

C# 规范

6.2.1 显式数值转换

  • 在检查上下文中,转换过程如下:
    • 如果操作数的值为 NaN 或无穷大,则抛出 System.OverflowException。
    • 否则,源操作数向零舍入到最接近的整数值。如果这个整数值在目标类型的范围内,那么这个值就是转换的结果。
    • 否则,将抛出 System.OverflowException。
  • 在未检查的上下文中,转换总是成功的,并按如下方式进行。
    • 如果操作数的值为 NaN 或无穷大,则转换结果为目标类型的未指定值。
    • 否则,源操作数向零舍入到最接近的整数值。如果这个整数值在目标类型的范围内,那么这个值就是转换的结果。
    • 否则,转换的结果是目标类型的未指定值。

环境

  • 编译器:Visual Studio 2013
  • Rimtime:.NET Framework 4.6.0
  • 操作系统:Windows 10 版本 1607
  • 中央处理器:英特尔酷睿 i7 920

window :

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

最佳答案

默认情况下,控制台应用程序编译为未选中。这就是为什么您的最后一个示例显示的值与显式使用 unchecked 的示例相同。

对于您的其余示例,您引用的规范部分适用:

  • 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.

(由我强调)。

Unspecified 表示您不能依赖结果。它可以是 0-2147483648 或任何其他内容。

我想弄清楚在你的特殊情况下到底发生了什么,但两种方式我都得到 -2147483648。因此很难追踪。

关于c# - 将 NaN 转换为 int 时,为什么值会根据是否分配给变量而变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42536954/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com