C++ Visual Studio 有符号整数的奇怪行为

C++ Visual Studio weired behaviour of signed integer

我的计算中有一些很长很长的边界常量。现在我有一个奇怪的行为,因为某些条件无效,因为数字是 "missinterpreted" 第一个输出是我想要使用的数字....在输出中你可以看到 - 符号被删除,所以我想到了下溢,但是当我添加一个 0 时,数字更高,输出是正确的....

我正在使用 Visual studio 2012

cout<<-2147483648<<endl;
cout<<-2147483649<<endl;
cout<<-21474836480<<endl;
cout<<-21474836490<<endl;
cout<<-214748364800<<endl;
cout<<-214748364900<<endl;

如您所见,前两行中的 - 符号已删除

2147483648
2147483647
-21474836480
-21474836490
-214748364800
-214748364900

知道这里有什么问题吗?

您应该仔细检查编译器给您的警告消息。如果您的代码没有产生警告,那么您应该增加编译器的警告生成级别。这段代码在 MSVC 编译器上会产生两个警告:

warning C4146: unary minus operator applied to unsigned type, result still unsigned

这基本上意味着,编译器将威胁前两个值作为 unsigned int,然后将其应用于一元减号运算符。要解决此问题,您应该隐式声明值类型:

cout << -(long long)2147483649 << endl;

不应忽略编译器警告!

由于您没有为整型文字添加后缀,编译器对小于 INT_MAX 的值使用 int,对 INT_MAX 和 U[=21 之间的值使用 unsigned int =].假设一个 2 补码 32 位平台,INT_MAX 是 2147483647,所以 2147483648 和 2147483648 是无符号的,并且如警告所述,对无符号类型应用减号仍然给出正值。所以结果是由于溢出。

正确的做法是 long 后缀 L 和 long long 后缀 LL:

cout<<-2147483648LL<<endl;
cout<<-2147483649LL<<endl;
cout<<-21474836480LL<<endl;
cout<<-21474836490LL<<endl;
cout<<-214748364800LL<<endl;
cout<<-214748364900LL<<endl;