首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在C/C++中int类型的最高值。为什么我不能在这个例子中正确地计算它?

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

Stack Overflow用户
提问于 2015-05-31 04:35:08
回答 2查看 4.4K关注 0票数 2

在示例程序中,输出2的幂,直到最高可能的整数值,我会遇到一个令人困惑的结果。

整数变量有符号,因此符号使用最高位。在我的机器上,整数的大小是4字节,即32位。我预计最高可能的整数值是2^31。

让我感到困惑的是:我可以计算的最高整数值是2^30。结果表明,2^31是最小整数值,而不是最大值。此外,2^32应该超过最大整数值,并且我期望得到一个不可预测的结果。取而代之的是0。

C中的示例:

代码语言:javascript
复制
#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++中的示例:

代码语言:javascript
复制
#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;
}

在这两个例子中,输出是相同的:

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-05-31 04:39:07

签名的整数溢出。

这是不确定的行为。因此,获取0是一个完全有效的未定义结果。

int中最大的整数。

我是2^31 - 1,不是2^31。注意,INT_MAX是一个奇数。

二补

您将遇到的大多数系统都不会使用符号震级来表示有符号的数字。相反,他们将使用二补

票数 7
EN

Stack Overflow用户

发布于 2015-05-31 09:34:47

执行pow*=2就像pow<<=1一样,它完美地解释了您所看到的行为。当初始1向左移动31次时,它位于整数的符号位中。它表示最小int值。当您再次移动它时,它会溢出,并且它在整数中只保留32位,因此得到0。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30553875

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档