读《C程序设计语言》笔记4

练习2-1:

  编写一个程序以确定分别由signed及unsigned限定的char、short、int及long类型变量的取值范围。采用打印标准头文件中的相应值以及直接计算两种方式实现:

  采用打印标准头文件中的相应值: 

1 #include <stdio.h>
2 #include <limits.h>
3 //determine ranges of types
4 int main()
5 {
6 printf("采用打印标准头文件limits.h中的相应值:\n");
7 //signed types
8 printf("signed char min = %d\n", SCHAR_MIN);
9 printf("signed char max = %d\n", SCHAR_MAX);
10 printf("signed short min = %d\n", SHRT_MIN);
11 printf("signed short max = %d\n", SHRT_MAX);
12 printf("signed int min = %d\n", INT_MIN);
13 printf("signed int max = %d\n", INT_MAX);
14 printf("signed long min = %ld\n", LONG_MIN);
15 printf("signed long max = %ld\n", LONG_MAX);
16 //unsigned types
17 printf("unsigned char max = %u\n", UCHAR_MAX);
18 printf("unsigned short max = %u\n", USHRT_MAX);
19 printf("unsigned int max = %u\n", UINT_MAX);
20 printf("unsigned long max = %lu\n", ULONG_MAX);
21 system("pause");
22 return 0;
23 }

  执行结果:

  这种实现方式没有什么需要讨论的,只需要知道相应的头文件和变量名称。

直接计算:

  

1 #include <stdio.h>
2 //determine ranges of types
3 int main()
4 {
5 printf("采用直接计算的方式:\n");
6 //signed types
7 printf("signed char min = %d\n", -(char)((unsigned char)~0>>1)-1);
8 printf("signed char max = %d\n", (char)((unsigned char)~0>>1));
9 printf("signed short min = %d\n", -(short)((unsigned short)~0>>1)-1);
10 printf("signed short max = %d\n", (short)((unsigned short)~0>>1));
11 printf("signed int min = %d\n", -(int)((unsigned int)~0>>1)-1);
12 printf("signed int max = %d\n", (int)((unsigned int)~0>>1));
13 printf("signed long min = %ld\n", -(long)((unsigned long)~0>>1)-1);
14 printf("signed long max = %ld\n", (long)((unsigned long)~0>>1));
15 //unsigned types
16 printf("unsigned char max = %u\n", (unsigned char)~0);
17 printf("unsigned short max = %u\n", (unsigned short)~0);
18 printf("unsigned int max = %u\n", (unsigned int)~0);
19 printf("unsigned long max = %lu\n", (unsigned long)~0);
20 system("pause");
21 return 0;
22 }

 执行结果:

  

小结:

  利用按位运算符进行计算。表达式:(char)((unsigned char)~0>>1)

  先把数字0的各个二进制位全部转换为1:取反,~0

  然后,将结果值转换为unsigned char类型:(unsigned char)~0

  再把这个unsigned char类型值右移一位以清除符号位:(unsigned char)~0 >> 1

  最后,把它转换为char类型:(char)((unsigned char)~0>>1)

  这一系列操作的最终结果就得到了signed类型字符的最大值。

  而其signed类型字符的最小值加负号后还需减去1才是最小值。

posted on 2011-07-12 16:15  Tony.Works  阅读(1235)  评论(9编辑  收藏  举报