为什么当通过 cin 存储的数字为负数时,无符号整数会产生很大的输出?

Why the unsigned integer produces a big output when the number stored through cin is negative?

我想知道无符号整数是如何工作的。

#include <iostream>
using namespace std;

int main(){
    int a = 50;             //basic integer data type
    unsigned int b;         //unsigned means the variable only holds positive values
    cout << "How many hours do you work? ";
    cin >> b;
    cout << "Your wage is " << b << " pesos.";

}

但是当我输入-5时,输出是

Your wage is 4294967291 pesos.

当我输入-1时,输出是

Your wage is 4294967295 pesos.

据推测,无符号整数具有正值。这是怎么发生的? 而且我只知道基本的 C++。有点看不懂

从有符号整数到无符号整数的转换是通过以下规则 (§[conv.integral]) 完成的:

  1. A prvalue of an integer type can be converted to a prvalue of another integer type.
    [...]
  2. If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type).

在你的例子中,unsigned 显然是一个 32 位类型,所以 -5 被减少模 232。所以 232 = 4,294,967,296 和 4,294,967,296 - 5 = 4,294,967,291.