【问题标题】:Is C# 5.0 explicit numeric conversion description correct?C# 5.0 显式数字转换描述是否正确?
【发布时间】:2014-01-16 10:14:27
【问题描述】:

从 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 值转换为整数类型时, 值被截断。如果得到的积分值在 目标值的范围,结果取决于溢出 检查上下文。在检查的上下文中,溢出异常是 抛出,而在未经检查的上下文中,结果是未指定的 目标类型的值。

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

【问题讨论】:

  • 你在困惑什么?您提供的示例与规范中描述的内容一致。 123.566 向下舍入到 123,在 int 范围内,所以结果是 int 123。
  • 我看到的唯一可能造成混淆的是“四舍五入”与“截断”,但它们只是描述相同操作的两种不同方式。
  • @Strilanc,谢谢。我没有注意到“趋于零”。

标签: c# explicit-conversion


【解决方案1】:

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

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

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

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

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

让我们在number line上分析一下;

如我们所见,当我们向零舍入时,结果将是 123

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

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

来自Wikipedia页面;

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

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

正如我们所见,当我们截断它时,结果将是123

【讨论】:

  • 我相信在 C# 中,表达式默认是未选中的。当然,您可以在 IDE 中更改它。这对于这种情况并不重要,就像在未经检查的上下文中一样,规范说“源操作数朝零四舍五入到最接近的整数值。”
  • @KrisVandermotten Yeap。我觉得我现在需要一杯咖啡。更新了我的答案。
【解决方案2】:

是的。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-17
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    相关资源
    最近更新 更多