无符号整数在C中溢出

女士

我编写了简单的C程序,以找到无符号整数可以达到的最大正数,如下所示。我的机器上整数的大小为4个字节。

#include <stdio.h>
#include <math.h>

main()
{
    unsigned int x = 1;
    int i = 1;

    for(; i <= 31; i++)
    {
        x = x * 2;
    }

    unsigned int y = pow(2, 31);

    printf("%d\n", x);
    printf("%d\n", y);
}

这两个xy越来越溢出和值-2147483648我认为它不应该溢出,因为在sizeof(int) = 4字节数unsigned int应为的机器上pow(2, 32) - 1任何人都可以让我知道为什么这越来越多了吗?

岩石滑轮

您要对未签名的int使用%u:

printf("%u\n", x);
printf("%u\n", y);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章