Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 无符号整数数组如何包含负整数?_C++_Arrays_Unsigned - Fatal编程技术网

C++ 无符号整数数组如何包含负整数?

C++ 无符号整数数组如何包含负整数?,c++,arrays,unsigned,C++,Arrays,Unsigned,我写这段代码只是为了看看如果我把一个负整数放入一个无符号整数数组会发生什么 #include <iostream> int main() { using namespace std; unsigned int array[4]; array[0]=4; array[1]=4; array[2]=2; array[3]=-2; cout << array[0] + array[1] + array[2] + ar

我写这段代码只是为了看看如果我把一个负整数放入一个无符号整数数组会发生什么

#include <iostream>

int main()
{
    using namespace std;

    unsigned int array[4];
    array[0]=4;
    array[1]=4;
    array[2]=2;
    array[3]=-2;

    cout << array[0] + array[1] + array[2] + array[3] << endl;

    unsigned int b;
    b=-2;
    cout << b <<endl;

    return 0;
}

对于有符号整数,第31位被视为符号位(假设4字节是整数大小)。对于无符号整数,根本没有符号位,即每一位都构成绝对值

对于有符号整数,最后一位用于保存符号值。因此,在您的例子中,当您将负整数赋给无符号整数时,最后一位表示数字,而不是符号值

负数通常以2的补码形式表示。所以

11111110  is represented as −1 if signed 
11111110  is represented as 254 if unsigned

有一个整数溢出。原因如下(数字转换为无符号整数)

当您这样做时(假设unsigned int为uint32\u t):


这里的
array[0]+array[1]+array[2]+array[3]
等于
4294967304
,它不适合于导致
8
的uint32
0x1 0000 0008
无符号整数溢出。您的-2值变成一个非常大的无符号整数,当与另一个无符号整数相加时,会导致溢出(结果大于可能的最大值
无符号int
值),结果比另一个无符号整数小2

例如:


< >将<代码> -2 < /COD> > <代码>未签名int < /代码>导致值<代码> 4294967294 <代码>(因为未签名的INT/COD>在您正在使用的C++实现中是32位)。
unsigned int
算术是按模执行的
4294967296
(或者通常是
UINT_MAX+1
)。因此,在无符号整数中,4+4+2+4294967294是8


从技术上讲,根据标准,这不称为“溢出”,因为标准定义的结果仅取决于
UINT\u MAX
的值。溢出是有符号整数算术超出其边界时的未定义行为。

预期输出是什么,实际输出是什么?确实会发生整数溢出。它只是碰巧是你喜欢的那种。这并不能保证有效,只是很常见。实际上,我很确定无符号溢出和有符号->无符号转换规则的定义方式是,第一个结果保证为8,第二个结果保证比最大无符号int少1,它是一个疯狂的屎。C++中的无符号运算是模2乘N,保证了,如果输出代码>数组[0 ] < /代码>等的实际值,这不应该只是它们的总和,这对你来说应该更清楚。
11111110  is represented as −1 if signed 
11111110  is represented as 254 if unsigned
 1111 1111 1111 1111 1111 1111 1111 1110 // -2
+0000 0000 0000 0000 0000 0000 0000 0100 //+ 4
-------------------------------------------
 0000 0000 0000 0000 0000 0000 0000 0010 //= 2
+0000 0000 0000 0000 0000 0000 0000 0100 //+ 4
-------------------------------------------
 0000 0000 0000 0000 0000 0000 0000 0110 //= 6
+0000 0000 0000 0000 0000 0000 0000 0010 //+ 2
-------------------------------------------
 0000 0000 0000 0000 0000 0000 0000 1000 //= 8 -> the result
array[0] = 4;
array[1] = 4;
array[2] = 2;
array[3] = -2; // You store 4294967294 here
unsigned int a = -2;
unsigned int b = 4;
unsigned int c = a + b; // result will be 2!