在C语言中,<limits.h>头文件的作用是定义了各种整数类型的取值范围和其他与限制相关的常量
它定义了有符号和无符号的char,short,int,long等数据类型的取值上限与下限,如CHAR_MIN,CHAR_MAX,SHRT_MIN,SHRT_MAX,INT_MIN,INT_MIX,INT_MAX,LONG_MIN,LONG_MAX 以及对应无符号类型的上限UCHAR_MAX,USHRT_MAX,UINT_MAX,ULONG_MAX.
使用头文件
#include <limits.h>
#include<stdio.h>
#include<limits.h>
int main() {
//打印有符号char类型的取值范围
printf("有符号char取值范围:%d到%d\n", SCHAR_MIN,SCHAR_MAX);
//打印无符号char类型的取值范围
printf("无符号的char取值范围:0到%u\n",UCHAR_MAX);
//打印有符号short类型的取值范围
printf("有符号short取值范围:%d 到%d\n",SHRT_MIN,SHRT_MAX);
//打印无符号short类型的取值变量
printf("无符号short取值范围:0 到%u\n",USHRT_MAX);
//打印有符号int类型的取值范围
printf("有符号int取值范围: %d 到%d\n",INT_MIN,INT_MAX);
//打印无符号int类型的取值范围
printf("无符号int取值范围:0 到%u\n",UINT_MAX);
//打印有符号long类型的取值范围
printf("有符号long取值范围:%ld 到%ld\n",LONG_MIN,LONG_MAX);
//打印无符号long类型的取值范围
printf("无符号long取值范围:0 到 %lu\n",ULONG_MAX);
return 0;
}
#include<stdio.h>
int main(){
printf("\n使用直接计算的方式:\n");
printf("signed char 取值范围: %d 到 %d\n", -(char)((unsigned char)~0 >> 1) - 1, (char)((unsigned char)~0 >> 1));
printf("unsigned char 取值范围: 0 到 %u\n", (unsigned char)~0);
printf("signed short 取值范围: %d 到 %d\n", -(short)((unsigned short)~0 >> 1) - 1, (short)((unsigned short)~0 >> 1));
printf("unsigned short 取值范围: 0 到 %u\n", (unsigned short)~0);
printf("signed int 取值范围: %d 到 %d\n", -(int)((unsigned int)~0 >> 1) - 1, (int)((unsigned int)~0 >> 1));
printf("unsigned int 取值范围: 0 到 %u\n", (unsigned int)~0);
printf("signed long 取值范围: %ld 到 %ld\n", -(long)((unsigned long)~0 >> 1) - 1, (long)((unsigned long)~0 >> 1));
printf("unsigned long 取值范围: 0 到 %lu\n", (unsigned long)~0);
return 0;
}