为什么(INT)double.NaN和(INT)double.PositiveInfinity为0? [英] Why (int)double.NaN and (int)double.PositiveInfinity are 0?
问题描述
在 C#,如果 0/0
你会得到一个例外。
in C#, if you 0/0
you get an exception.
但是,如果你 0.0 / 0
或 0.0 / 0.0
你 double.NaN
和 double.Infinity
,分别为。
But if you 0.0/0
or 0.0/0.0
you get double.NaN
and double.Infinity
, respectively.
但如果你投这些结果为<$ C 。$ C> INT ,你得到0
but if you cast these results to int
, you get 0.
> (int)double.PositiveInfinity
0
> (int)double.NaN
0
为什么会出现这种情况?是不是应该给铸造错误,因为无穷显然不是一个零运行?
Why is this the case? Isn't the runtime supposed to give casting error because infinity is clearly not a zero?
推荐答案
这要看是什么样的背景下你在。如果你使用检查
情况下,你会得到一个异常。该规范的有关条文是6.2.1节:
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:
对于从float或double到整型的转换,处理取决于溢出检查上下文(§7.6.12),其中发生转换:
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:
- 在选中的情况下,转换过程如下:
- 如果操作数的值是NaN或无穷大,则引发System.OverflowException。
- 否则,源操作数取整向零到最接近的整数值。如果该整数值处于目标类型的范围内,那么这个值就是转换的结果。
- 否则,则引发System.OverflowException。
- 如果操作数的值是NaN或无穷大,转换的结果是目标类型的一个未经指定的值。
- 否则,源操作数朝向零舍入到最接近的整数值。如果该积分值是所述目标类型的范围内,则该值是转换的结果。
- 否则,转换的结果是目标类型的一个未指定的值。
因此,在unchecked上下文中,答案的不是的一定是0 - 这是一个不确定的
INT
值。事实上,在我的测试中,它出现为int.MinValue
,而不是0 unchecked上下文中。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 asint.MinValue
rather than 0 in an unchecked context.但是从根本上,如果你想要做的检查,使用(至少是对于那些表达式)checked环境。
But fundamentally, if you want to do checking, use a checked context (at least for that expression).
这篇关于为什么(INT)double.NaN和(INT)double.PositiveInfinity为0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!