gpt4 book ai didi

c++ - C/C++ 中 int 类型的最大值。为什么我不能在这个例子中正确计算它?

转载 作者:太空狗 更新时间:2023-10-29 23:50:24 26 4
gpt4 key购买 nike

在打印 2 的幂直到最大可能整数值的示例程序中,我遇到了一个令人困惑的结果。

整数变量是有符号的,所以最高位用于符号。在我的机器上,整数的大小是 4 个字节,即 32 位。我希望最大可能的整数值为 2^31。

让我感到困惑的是:我能计算出的最大整数值是 2^30。结果显示 2^31 是最小整数值而不是最大值。此外,2^32 应该超过最大整数值,我预计会出现不可预测的结果。相反,它是 0。

C 中的示例:

#include <stdio.h>
#include <limits.h>

int main(void) {
int exp;
int pow = 1;

for (exp = 0; exp < 33; exp++) {
printf("2 to the power of %d is %d\n", exp, pow);
pow *= 2;
}

printf("%d\n", INT_MIN);
printf("%d\n", INT_MAX);

return 0;
}

C++ 示例:

#include <iostream>
#include <limits>

using namespace std;

int main(void) {
int pow = 1;

for (int exp = 0; exp < 33; exp++) {
cout << "2 to the power of " << exp << " is " << pow << endl;
pow *= 2;
}

int imin = std::numeric_limits<int>::min(); // minimum value
int imax = std::numeric_limits<int>::max();

cout << imin << endl;
cout << imax << endl;

return 0;
}

两个示例中的输出相同:

2 to the power of 0 is 1
2 to the power of 1 is 2
2 to the power of 2 is 4
2 to the power of 3 is 8
2 to the power of 4 is 16
2 to the power of 5 is 32
2 to the power of 6 is 64
2 to the power of 7 is 128
2 to the power of 8 is 256
2 to the power of 9 is 512
2 to the power of 10 is 1024
2 to the power of 11 is 2048
2 to the power of 12 is 4096
2 to the power of 13 is 8192
2 to the power of 14 is 16384
2 to the power of 15 is 32768
2 to the power of 16 is 65536
2 to the power of 17 is 131072
2 to the power of 18 is 262144
2 to the power of 19 is 524288
2 to the power of 20 is 1048576
2 to the power of 21 is 2097152
2 to the power of 22 is 4194304
2 to the power of 23 is 8388608
2 to the power of 24 is 16777216
2 to the power of 25 is 33554432
2 to the power of 26 is 67108864
2 to the power of 27 is 134217728
2 to the power of 28 is 268435456
2 to the power of 29 is 536870912
2 to the power of 30 is 1073741824
2 to the power of 31 is -2147483648
2 to the power of 32 is 0
-2147483648
2147483647

最佳答案

有符号整数溢出。

这是未定义的行为。所以得到 0 是一个完全有效的未定义结果。

int 中的最大整数。

它是 2^31 - 1,而不是 2^31。请注意,INT_MAX 是奇数。

补码

您将遇到的大多数系统都不会使用 Signed Magnitude来表示带符号的数字。相反,他们将使用 Two's Complement .

关于c++ - C/C++ 中 int 类型的最大值。为什么我不能在这个例子中正确计算它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30553875/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com