c语言基础——每日一题(1)

题目:编写一个程序以确定的分别由signed及unsigned限定的char,short,int与long类型变量的取值范围。采用打印标准头文件的相应值以及直接计算两种方式实现。
第一种方法:库函数limits.h

//采用limits.h库求值
int main()
{   //singed 类型
	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);
	//unsiged 类型
	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;
}

第二种方法

//通过计算求值
int main()
{
//	signed类型
	printf("signed char min= %d\n", -(char)((unsigned char)~0 >> 1));
	printf("signed char max= %d\n", (char)((unsigned char)~0 >> 1));
	printf("signed short min= %d\n", -(short)((unsigned short)~0 >> 1));
	printf("signed short max= %d\n", (short)((unsigned short)~0 >> 1));
	printf("signed int min= %d\n", -(int)((unsigned int)~0 >> 1));
	printf("signed int max= %d\n", (int)((unsigned int)~0 >> 1));
	printf("signed long min= %ld\n", -(long)((unsigned long)~0 >> 1));
	printf("signed long max= %ld\n", (long)((unsigned long)~0 >> 1));
//     unsigned类型
	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);
}

注:(unsigned char)~0是将无符号的char类型所有位全部置1,此处不能使用有符号的类型,因为有符号类型会采用算术移位,用符号位填充,就达不到将第一位置成0的效果。

你可能感兴趣的:(c语言基础练习,c语言,1024程序员节)