This question already has answers here:
Unsigned int in C behaves negative
                                
                                    (8个答案)
                                
                        
                                5年前关闭。
            
                    
我编写了简单的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);

关于c - 无符号整数在C中溢出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26223316/

10-14 14:48
查看更多