据我了解,这应该会给你一个溢出错误,当我这样写时:
public static void Main()
{
Console.WriteLine(int.MaxValue - int.MinValue);
}
它确实给我一个溢出错误。
但是:
public static void Main()
{
Console.WriteLine(test());
}
public static Int32 test(int minimum = int.MinValue, int maximum = int.MaxValue)
{
return maximum - minimum;
}
将输出-1 为什么要这样做?它应该抛出错误,因为它显然是溢出!
最佳答案
int.MaxValue - int.MinValue
= int 无法保存的值。因此,数字回绕到 -1。
就像 2147483647-(-2147483648) = 4294967295 不是 int
The value of this constant is -2,147,483,648; that is, hexadecimal 0x80000000.
The value of this constant is 2,147,483,647; that is, hexadecimal 0x7FFFFFFF.
来自 MSDN
When integer overflow occurs, what happens depends on the execution context, which can be checked or unchecked. In a checked context, an OverflowException is thrown. In an unchecked context, the most significant bits of the result are discarded and execution continues. Thus, C# gives you the choice of handling or ignoring overflow.
关于c# - 为什么 int.MaxValue - int.MinValue = -1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23833999/