2017-09-03 6 views
-3

나는 내가해야 할 일에 잘 작동하는 것 같은 다음 프로그램을 작성했다. 그러나, 나는 UINT_MAX가 저를주는 이유 -1 출력하지 4294967295 (의 printf()를 통해), 여기에 지정된 궁금 : https://www.tutorialspoint.com/c_standard_library/limits_h.htmUINT_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); 

}

나는 세부 사항을 생략하거나 뭔가를 오해 있습니까?

+4

'size_t' ('sizeof' 결과)에'% zu'를 사용하고'unsigned int'에'% u'를 사용하십시오. – BLUEPIXY

답변

3

%d 같다 보완합니다.

부호없는 정수의 최대 값을 부호있는 정수처럼 포맷하고 인쇄하려고합니다. 부호있는 정수는 부호없는 정수의 최대 값을 가질 수 없으므로 (부호 용으로 최상위 비트가 사용됨) 오버플로되고 음수를 얻기 시작합니다.

이에 예를 수정하면

는 :

printf("**unsigned int**\nStorage size: %zu bytes \t Maximum value: %u\n\n", sizeof(unsigned int), UINT_MAX);

그것은 당신에게 당신이 기대하는 결과를 제공 할 것입니다.

다른 사람도 지적한대로 %zusizeof의 결과에 대한 올바른 지정자입니다.

+0

더 나은 [printf] (http://en.cppreference.com/w/) c/io/fprintf) C 특정 참조 사이트. – EsmaeelE

1

부호가 int 인 것으로 예상하는 %d을 사용했기 때문에. 대신 % u를 사용하십시오. 두의에서

는 -1 이진 표현이 signed integer가 (: http://www.cplusplus.com/reference/cstdio/printf/ 자세한 내용은이 링크를 참조)을 의미 같은 printf에 전달되는 형식 문자열 UINT_MAX

관련 문제