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

标签 c# modulus overflowexception

<分区>

在 7.8.3 中。关于 Remainder 运算符的 C# 规范的声明如下:

If the left operand is the smallest int or long value and the right operand is -1, a System.OverflowException is thrown.

因此 int.MinValue % -1 将导致 OverflowException。我想了解为什么?

最佳答案

在二进制补码运算中,数据类型的范围从 (-2**n) 到 (2**n - 1)(其中“n”比数据类型中的位数少 1)。

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

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

关于c# - 为什么 int.MinValue % -1 会导致 OverflowException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33928048/

相关文章:

java - 数组索引的模运算

java - 如何在 while 循环中使用模数来获取整数的各个数字?

c - 大整数模幂

c# - 为什么相加两个结果大于 int.MaxValue 的大整数不会抛出溢出异常?

c# - 算术检查语句放在哪里?

c# - 应用程序需要先在 GAC 中安装 log4net 程序集

c# - 解析 1 TB 的文本并有效地计算每个单词的出现次数

c# - 如何访问excel文件的当前行索引?

c# - 如何停止在整数除法时抛出 OverflowException?

c# - 从另一个 C# 程序启动 C# 程序