gpt4 book ai didi

c# - 为什么 (int)double.NaN 和 (int)double.PositiveInfinity 为 0?

转载 作者:IT王子 更新时间:2023-10-29 04:27:52 25 4
gpt4 key购买 nike

C#中,如果您0/0,您会得到一个异常。

但是如果你0.0/00.0/0.0 你得到double.NaNdouble.Infinity , 分别。

但是如果将这些结果转换为 int,您将得到 0。

> (int)double.PositiveInfinity
0
> (int)double.NaN
0

为什么会这样?难道运行时不应该给出转换错误,因为无穷大显然不是零吗?

最佳答案

这取决于您所处的上下文类型。如果您使用checked 上下文,您将得到一个异常。规范的相关部分是第 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.

因此在未经检查的上下文中,答案不一定是 0 - 它是一个未指定的 int 值。事实上,在我的测试中,它在未经检查的上下文中显示为 int.MinValue 而不是 0。

但从根本上说,如果您想进行检查,请使用已检查的上下文(至少对于该表达式)。

关于c# - 为什么 (int)double.NaN 和 (int)double.PositiveInfinity 为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14244668/

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