【发布时间】: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,谢谢。我没有注意到“趋于零”。