【C语言】练习2-1

  •  题目来源:《The C programming language》中的习题P27
  •  练习2-1: 编写一个程序以确定分别由signed及unsigned限定的char、short、int与long类型变量的取值范围。采用打印标准头文件中的相应值以及直接计算两种方式实现。后一种方法的实现较困难一些,因为要确定各种浮点类型的取值范围。

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

#include <stdio.h>
#include <limits.h>

int main()
{
    printf("采用打印标准头文件limits.h中的相应值:\n");
    //signed types
    printf("signed char min = %d\n", SCHAR_MIN);
    printf("signed char max = %d\n", SCHAR_MAX);
    printf("signed short min = %d\n", SHRT_MIN);
    printf("signed short max = %d\n", SHRT_MAX);
    printf("signed int min = %d\n", INT_MIN);
    printf("signed int max = %d\n", INT_MAX);
    printf("signed long min = %ld\n", LONG_MIN);
    printf("signed long max = %ld\n", LONG_MAX);
    //unsigned types
    printf("unsigned char max = %u\n", UCHAR_MAX);
    printf("unsigned short max = %u\n", USHRT_MAX);
    printf("unsigned int max = %u\n", UINT_MAX);
    printf("unsigned long max = %lu\n", ULONG_MAX);
    return 0;
}

  执行结果:

  直接计算的方式:

#include <stdio.h>
//determine ranges of types
int main()
{
printf("采用直接计算的方式:\n");
//signed types
printf("signed char min = %d\n", -(char)((unsigned char)~0>>1)-1);
printf("signed char max = %d\n", (char)((unsigned char)~0>>1));
printf("signed short min = %d\n", -(short)((unsigned short)~0>>1)-1);
printf("signed short max = %d\n", (short)((unsigned short)~0>>1));
printf("signed int min = %d\n", -(int)((unsigned int)~0>>1)-1);
printf("signed int max = %d\n", (int)((unsigned int)~0>>1));
printf("signed long min = %ld\n", -(long)((unsigned long)~0>>1)-1);
printf("signed long max = %ld\n", (long)((unsigned long)~0>>1));
//unsigned types
printf("unsigned char max = %u\n", (unsigned char)~0);
printf("unsigned short max = %u\n", (unsigned short)~0);
printf("unsigned int max = %u\n", (unsigned int)~0);
printf("unsigned long max = %lu\n", (unsigned long)~0);
return 0;
}

  执行结果:

  备注:

  • <limits.h>包含了定义char int short long类型取值的最大值和最小值用常量表示(例如SCHAR_MIN = -128), 所以直接打印即可。
  • 如果直接计算的话,则需要用到按位运算符~和右移运算符>>,对于-(char)((unsigned char)~0 >> 1)解释:

    a: (unsigned char)~0用二进制表示为:11111111

           b: (unsigned char)~0 >> 1,将(unsigned char)~0逻辑右移1位,结果为:01111111

           c: (char)((unsigned char)~0 >> 1),将((unsigned char)~0 >> 1)由无符号类型强制转换为有符号类型

           d: -(char)((unsigned char)~0 >> 1),得到的二进制结果为11111111,最高位为符号为,对应的十进制数为:-127

  • 因为绝大部分机器采用补码方式表示有符号整数,所以需要在-(char)((unsigned char)~0 >> 1)的基础上再减去1,才是真正的最小值。

  参考资料:

  [1] http://www.cnblogs.com/wangzhiyu811/archive/2011/07/12/2104377.html

  [2] http://blog.csdn.net/roma823/article/details/6367142

posted @ 2014-06-08 15:42  NW_KNIFE  阅读(434)  评论(0编辑  收藏  举报