将unsigned int添加到int [英] adding unsigned int to int
问题描述
#include <iostream>
int main ()
{
using namespace std;
unsigned int i = 4;
int a = -40;
cout<<a+i<<endl;
return 0;
}
执行此操作会得到4294967260
Executing this gives me 4294967260
我知道发生了一个转换,从一个signed int到unsigned int,
,但是如何和为什么这个特定的值?
我注意到它接近的总和| 2147483647 | + 2147483647
I know there's a conversion taking place, from a signed int to unsigned int, but how and why this particular value? I noticed it's close to the sum of | 2147483647 | + 2147483647
推荐答案
当 unsigned int
和 int
添加在一起,则 int
首先转换为 unsigned int
添加发生(并且结果也是 unsigned int
)。
When an unsigned int
and an int
are added together, the int
is first converted to unsigned int
before the addition takes place (and the result is also an unsigned int
).
-1,同时是第一个否定number,实际上等于最大的无符号数 - 也就是(unsigned int)-1 === UINT_MAX
。
-1, while being the first negative number, is actually equivalent to the largest unsigned number - that is, (unsigned int) -1 === UINT_MAX
.
-2无符号形式为 UINT_MAX - 1
等等,因此 -40 === UINT_MAX - 39 === 4294967256
(当使用32位整数时)。
-2 in unsigned form is UINT_MAX - 1
, and so on, so -40 === UINT_MAX - 39 === 4294967256
(when using 32bit ints).
当然,添加4然后给出你的答案:
4294967256 + 4 = 4294967260
。
Of course, adding 4 then gives your answer:
4294967256 + 4 = 4294967260
.
这是一个伟大的测验,你可以在C中学习一些整数的规则a href =http://blog.regehr.org/archives/721> http://blog.regehr.org/archives/721
This is a great quiz where you can learn some of the rules of integers in C (and similarly C++): http://blog.regehr.org/archives/721
这篇关于将unsigned int添加到int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!