为什么UINT_MAX返回-1?
我写了下面的程序,它似乎对我需要做的事很好。但是,我不知道为什么UINT_MAX是给我-1输出(通过的printf()),而不是4294967295,如下规定:https://www.tutorialspoint.com/c_standard_library/limits_h.htm为什么UINT_MAX返回-1?
#include <stdio.h>
#include <limits.h>
int main() {
printf("Below is the storage size for various data types.\n\n");
//char data type
printf("**char**\nStorage size: %d byte \t Minimum value: %d \t Maximum value: %d\n\n", sizeof(char), CHAR_MIN, CHAR_MAX);
//signed char data type
printf("**signed char**\nStorage size: %d byte \t Minimum value: %d \t Maximum value: %d\n\n", sizeof(signed char), SCHAR_MIN, SCHAR_MAX);
//unsigned char data type
printf("**unsigned char**\nStorage size: %d byte \t Maximum value: %d\n\n", sizeof(unsigned char), UCHAR_MAX);
//int data type
printf("**int**\nStorage size: %d bytes \t Minimum value: %d \t Maximum value: %d\n\n", sizeof(int), INT_MIN, INT_MAX);
//unsigned int data type
printf("**unsigned int**\nStorage size: %d bytes \t Maximum value: %d\n\n", sizeof(unsigned int), UINT_MAX);
}
难道我省略了细节或误解的东西?
%d
传递给printf
格式字符串意味着signed integer
(有关详细信息,请参阅以下链接:http://www.cplusplus.com/reference/cstdio/printf/)。
您正在尝试格式化和打印无符号整数的最大值,就像它是有符号整数一样。由于有符号整数无法保存无符号整数的最大值(最高有效位用于符号),因此它会溢出并开始变为负数。
如果您修改您的例子是:
printf("**unsigned int**\nStorage size: %zu bytes \t Maximum value: %u\n\n", sizeof(unsigned int), UINT_MAX);
它会给你你所期望的结果。
正如其他人所指出的,%zu
对于sizeof
的结果是正确的说明符。
使用[printf](http://en.cppreference.com/w/) c/io/fprintf)C特定的参考站点。 – EsmaeelE
因为您使用%d
其中预计签署int
。改用%u代替。
二的补-1二进制表示相同 UINT_MAX
使用'%zu'代替'size_t'('sizeof'的结果)和'%u'代替'unsigned int' – BLUEPIXY