为什么两次减去int.MinValue导致int.MinValue?

Ali*_*son 0 c#

我试图获得一个数字的正值而不使用Math.Abs这样的:

int small = -1000;
Console.WriteLine(small - small - small);
int big = int.MinValue;
Console.WriteLine(big - big - big);
Run Code Online (Sandbox Code Playgroud)

第一个工作正常,我得到1000印刷,但对于第二种情况,它得到-2147483648而不是积极的2147483648.

我怀疑这与整数溢出有关,但我认为这没有意义,因为操作的结果不应该溢出整数边界.

例如:

(-2147483648) - (-2147483648) = 0
0 - (-2147483648) = 2147483648
Run Code Online (Sandbox Code Playgroud)

要么

(-2147483648) - (-2147483648) - (-2147483648) = 2147483648
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

Mik*_*bel 5

正如你所说:

(-2147483648) - (-2147483648) = 0
0 - (-2147483648) = 2147483648
Run Code Online (Sandbox Code Playgroud)

从数学角度来说,这是有效的.但是,int.MaxValue2147483647. 2147483648相当于int.MaxValue + 1,溢出,将结果包装回来-2147483648.

  • @Alisson有趣的事实:将你的代码包装在`checked {....}`中,你会得到一个溢出异常. (2认同)