Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
C# の数値型の損失情報について少し混乱しています。
私がこれを行うとき:
int x = 32780; short y = (short)x;
結果は-32756で、予想される32767ではありません。なぜですか? これはどのように計算されますか?
short の範囲: -32768 ~ 32767 int の範囲: -2,147,483,648 ~ 2,147,483,647
オーバーフローがあります。数値を最大値に制限したい場合は、整数を と比較することでこれを回避できますshort.MaxValue。
short.MaxValue
short y; if (x > short.MaxValue) { y = short.MaxValue; } else if (x < short.MinValue) { y = short.MinValue; } else { y = (short)x; }