为什么-2?为什么不-3 -1? [英] Why -2? Why not -3 or -1?

查看:132
本文介绍了为什么-2?为什么不-3 -1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Program
{
    static void Main(string[] args)
    {
        int a = Int32.MaxValue;
        int b = Int32.MaxValue;             

        Console.WriteLine(a+b);
    }
}



OUTPUT:-2

OUTPUT: -2

发生溢出,但它是如何计算和找到-2结果?

Overflow occurs but how does it calculate and find -2 as a result?

推荐答案

数行是一个循环:

     -1    0
-2            1
...              ...
...              ...
...              ...
   -2147483648 2147483647

添加到1之间的数值。在这个圈子里的影响正在一步顺时针方向之一。结果
添加1到2147483647(= int.MaxValue)把你带到-2147483648(= int.MinValue)

Adding 1 to a number is in effect taking one step clockwise on this circle.
Adding 1 to 2147483647 (=int.MaxValue) takes you to -2147483648 (=int.MinValue)

如果你开始在2147483647,并就圆2147483647步骤,您在-2结束。

If you start at 2147483647 and take 2147483647 steps on the circle, you end up at -2.

什么是好笑:我们说的溢出发生在int.MaxValue => int.MinValue,并在十进制表示确实如此,但在二进制表示,溢出在-1(全1)=> 0(全0)时,对圆的相对侧

What's funny about this: we say overflow occurs at int.MaxValue => int.MinValue, and in decimal notation it does, but in binary notation, the overflow occurs at -1 (all 1's) => 0 (all 0's), on the opposite side of the circle.

这篇关于为什么-2?为什么不-3 -1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆