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 仕様の両方の説明は正しいです。

C# 式はuncheckedデフォルトです。太字の部分をもう一度見てください。

  • チェックされていないコンテキストでは、変換は常に成功し、次のように進みます。
    • オペランドの値が NaN または無限の場合、変換の結果は変換先の型の指定されていない値になります。
    • それ以外の場合、ソース オペランドはゼロに向かって最も近い整数値に丸められます。この整数値が変換先の型の範囲内にある場合、この値は変換の結果です。

まず、仕様の内容を見てみましょう。

ゼロに向かって最も近い整数値に丸められます

それを分析しましょうnumber line;

ここに画像の説明を入力

ご覧のとおり、ゼロに向かって丸めると、結果は 123 になります。

次に、MSDN の内容を見てみましょう。

double または float 値から整数型に変換すると、値が切り捨てられる

ページからWikipedia;

数学とコンピューター サイエンスでは、切り捨ては小数点以下の桁数を制限するための用語です。

場合によっては、切り捨てによって丸めと同じ結果が得られることがありますが、切り捨ては桁の切り上げまたは切り下げを行いません。 指定された桁で切り捨てられるだけです。

ご覧のとおり、切り捨て123た場合も結果になります。

于 2013-12-29T10:26:47.857 に答える
2

はい、そうです。

(これは長くて適格な回答ではないことを申し訳ありませんが、他に何も求めていません. )

于 2013-12-29T10:19:57.947 に答える