将数字添加到整数变量中,其值已经为int.MaxValue [英] Adding number to integer variable with value already as int.MaxValue

查看:56
本文介绍了将数字添加到整数变量中,其值已经为int.MaxValue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

令人惊讶的是,第一行引发了提到的错误.但是for循环有效.也执行for循环并执行加法.似乎在处理整数时我们正在绕圈移动.为什么会发生这种情况的任何见解?

 //  int i = int.MaxValue + 100; //错误:操作在检查模式下在编译时溢出
// 以下作品
 for ( int  i =  int  .MaxValue ; i >   0 ; i ++)
{
  i = i +  10 ;

  Console.WriteLine(i);
} 

解决方案

因为整数确实确实会绕圈移动!如果您超过了MaxValue,那么您将陷入负数范围.在有符号整数中设置最高位的任何内容均为负数,并且最大值为否则为1的32位字中的单个0位.如果在其中添加一个值,则新值将设置最高位,因此为负.
不会引发溢出异常有点烦人,但这就是生命!

另一行在编译时会抱怨,因为它正确地指出,如果将数字加到最大值,它将溢出.


工作"是什么意思?它无声地溢出了.


MaxValue +1 == Maxvalue *-1;


因此,当它位于顶部时,它将返回到Int范围内的最大负值

Surprisingly, the first line throws mentioned error. But the for loop works. For loop executed too and performs addition as well. It seems as if we are moving in circles while dealing with integers. Any insight on why this happens?

// int i = int.MaxValue + 100; // Error: The operation overflows at compile time in checked mode
// Following works
for (int i = int.MaxValue; i > 0; i++)
{
  i = i + 10;

  Console.WriteLine(i);
}

解决方案

Because integers do indeed move in circles! If you exceed the MaxValue, then you get into negative territory. Anything with the top bit set in a signed integer is a negative number, and the Max value is a single 0 bit in an otherwise 1 filled 32 bit word. If you add a value to that, then the new value will have the top bit set, and thus be negative.
It''s a little annoying that it doesn''t throw an overflow exception, but that''s life!

The other line complains at compile time because it rightly spots that if you add a number to it''s maximum value, it will overflow.


What do you mean with ''works''? It silently overflows, that''s all.


MaxValue +1 == Maxvalue *-1;


So when it is at the top it will return to the maximum negative value in the Int range


这篇关于将数字添加到整数变量中,其值已经为int.MaxValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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