为什么多头多头2147483647 + 1 = -2147483648? [英] why does long long 2147483647 + 1 = -2147483648?
问题描述
为什么此代码没有打印相同的数字? :
Why doesn't this code print same number? :
long long a, b;
a = 2147483647 + 1;
b = 2147483648;
printf("%lld\n", a);
printf("%lld\n", b);
我知道int变量的最大数量为2147483647,因为int变量为4个字节。
但是,正如我所知,long long变量是8个字节,但是为什么该代码如此起作用?
I know that int variable's maximum number is 2147483647 because int variable is 4 byte. But as I know, long long variable is 8 byte, but why does that code act like that?
推荐答案
2147483647 + 1
被计算为两个 ints
的总和,因此会溢出。
2147483647 + 1
is evaluated as the sum of two ints
and therefore overflows.
2147483648
太大,无法容纳在 int
中,因此编译器认为它是 long
(或MSVC中的 long long
)。因此,它不会溢出。
2147483648
is too big to fit in an int
and is therefore assumed by the compiler to be a long
(or a long long
in MSVC). It therefore does not overflow.
要使用 long long
进行求和,请使用适当的常量后缀,即
To perform the summation as a long long
use the appropriate constant suffix, i.e.
a = 2147483647LL + 1;
这篇关于为什么多头多头2147483647 + 1 = -2147483648?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!