为什么int.MinValue%-1会导致和OverflowException

本文关键字:OverflowException int MinValue%-1 为什么 | 更新日期: 2023-09-27 18:24:18

在7.8.3中。关于余数运算符的C#规范规定如下:

如果左操作数是最小的int或long值,而右操作数操作数为-1,则引发System.OverflowException。

因此,int.MinValue % -1将导致OverflowException。我想知道为什么?

为什么int.MinValue%-1会导致和OverflowException

在two的补码算术中,数据类型的范围从(-2**n)到(2**n-1)(其中'n'比数据类型中的位数少1)。

例如,一个16位带符号整数的有效范围为-32768(-2**15)到32767(2**15-1)。

-32768/-1=+32768,超出了16位带符号整数的有效范围。

相关文章:
  • 没有找到相关文章