练习2-1 编写一个程序一确定分别由signed及unsigned限定的char,short,int及long类型变量的取值范围。采用打印标准头文件中的相应值以及直接计算两种方式实现。通过直接计算来确定浮点类型的取值范围是一项难度很大的任务。

不太了解如何打印取值范围。直接看答案。

通过打印头文件实现 <limits.h>

 1 #include <stdio.h>
 2 #include <limits.h>
 3 main()
 4 {
 5 /* signed types */
 6 
 7 printf("signed char min = %d\n", SCHAR_MIN);
 8 printf("signed char max = %d\n", SCHAR_MAX);
 9 printf("signed short min = %d\n", SHRT_MIN);
10 printf("signed short max = %d\n", SHRT_MAX);
11 printf("signed int min = %d\n", INT_MIN);
12 printf("signed int max = %d\n", INT_MAX);
13 printf("signed long min = %d\n", LONG_MIN);
14 printf("signed long max = %d\n", LONG_MAX);
15 
16 /*unsigned types*/
17 printf("unsigned char max = %d\n", UCHAR_MAX);
18 printf("unsigned short max = %d\n", USHRT_MAX);
19 printf("unsigned int max = %d\n", UINT_MAX);
20 printf("unsigned long max = %d\n", ULONG_MAX);
21 
22 return 0;
23 }

 直接计算打印取值范围;

 1 #include <stdio.h>
 2 /*determine ranges of types*/
 3 main()
 4 {
 5 /* signed ranges of types*/
 6 
 7 printf(" signed char min = %d \n", -(char)((unsigned char) ~0 >> 1));
 8 
 9 printf(" signed char max = %d \n", (char)((unsigned char) ~0 >> 1));
10 
11 printf(" signed short min = %d \n", -(short)((unsigned short) ~0 >> 1));
12 
13 printf(" signed short max = %d \n", (short)((unsigned short) ~0 >> 1));
14 
15 printf(" signed int min = %d \n", -(int)((unsigned int) ~0 >> 1));
16 
17 printf(" signed int max = %d \n", (int)((unsigned int) ~0 >> 1));
18 
19 printf(" signed long min = %d \n", -(long)((unsigned long) ~0 >> 1));
20 
21 printf(" signed long max = %d \n", (long)((unsigned long) ~0 >> 1));
22 
23 
24 /*unsigned types*/
25 
26 printf(" unsigned char max = %d \n",(unsigned char) ~0);
27 
28 printf(" unsigned int max = %d \n",(unsigned int) ~0);
29 
30 printf(" unsigned short max = %d \n",(unsigned short) ~0);
31 
32 printf(" unsigned long max = %d \n",(unsigned long) ~0);
33 
34 
35 return 0;
36 }

 

 

输出:

signed char min = -127
signed char max = 127
signed short min = -32767
signed short max = 32767
signed int min = -2147483647
signed int max = 2147483647
signed long min = -2147483647
signed long max = 2147483647
unsigned char max = 255
unsigned int max = -1
unsigned short max = 65535
unsigned long max = -1

posted @ 2013-10-28 22:14  _Jango  阅读(1747)  评论(0编辑  收藏  举报