1

从 float 和 double 到 C# 5.0 规范(第 6.2.1 段)中描述的任何整数类型的显式数字转换如下:

• 对于从 float 或 double 到整数类型的转换,处理取决于发生转换的溢出检查上下文(第 7.6.12 节):

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

同时在MSDN中描述的相同转换规则如下:

当您从 double 或 float 值转换为整数类型时,该值将被截断。如果生成的整数值超出目标值的范围,则结果取决于溢出检查上下文。在已检查的上下文中,会引发 OverflowException,而在未检查的上下文中,结果是目标类型的未指定值。

评估这种转换,例如“(int)123.566”,得到“123”。规范中的描述是否正确?

4

2 回答 2

4

MSDNC# 5.0 Specification中的描述都是正确的。

默认情况下是 C# 表达式unchecked。再看一下粗体部分;

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

首先,让我们看看规范是怎么说的:

向零舍入到最接近的整数值

让我们来分析一下number line

在此处输入图像描述

正如我们所看到的,当我们向零舍入时,结果将是 123 。

其次,我们来看看 MSDN 是怎么说的:

当您从 double 或 float 值转换为整数类型时,该值将被截断

Wikipedia页面;

在数学和计算机科学中,截断是限制小数点右边位数的术语。

请注意,在某些情况下,截断会产生与舍入相同的结果,但截断不会向上或向下舍入数字; 它只是在指定的数字处切断。

正如我们所看到的,结果也将是123我们截断它时的结果。

于 2013-12-29T10:26:47.857 回答
2

是的。

(很抱歉,这不是一个长而合格的答案,但您没有要求其他任何内容。)

于 2013-12-29T10:19:57.947 回答