c# - 为什么 int.MaxValue - int.MinValue = -1?

标签 c#

据我了解,这应该会给你一个溢出错误,当我这样写时:

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

Int32.MinValue Field

The value of this constant is -2,147,483,648; that is, hexadecimal 0x80000000.

Int32.MaxValue Field

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/

相关文章:

c# - 无法在 SaveState/LoadState 之后设置 MediaElement Source

c# - flowlayoutpanel 和水平滚动条问题

c# - 在列表框项之间绘制自定义元素

c# - 我如何发现给定日期的四分之一

c# - 字符串填充不占用相同的字符间距

c# - SqlDataAdapter 不删除记录

c# - 无法在 Mac OS X 上的 C# 项目中引用 FSharp.Core

c# - 从套接字读取传入数据?

c# - Linq to SQL 类 - 存储过程签名更改

c# - 如何撤消未更改文件的未决更改?