way1:
通过打印标准的头文件中的相应的值来完成
#include <iostream>
#include <climits>
using namespace std;
int main()
{
cout << "Size:" << endl;
cout << "int is " << sizeof (int) << "bytes." << endl;
cout << "short is " << sizeof (short) << "bytes." << endl;
cout << "long is " << sizeof (long) << "bytes." << endl << endl;
cout << "Bits per byte = " << CHAR_BIT << endl << endl;
cout << "Maximum values:" << endl;
cout << "int: " << INT_MAX << endl;
cout << "short: " << SHRT_MAX << endl;
cout << "long: " << LONG_MAX << endl;
cout << "char: " << CHAR_MAX << endl;
cout << "signed char: " << SCHAR_MAX << endl;
cout << "unsigned int: " << UINT_MAX << endl;
cout << "unsigned short:" << USHRT_MAX << endl;
cout << "unsigned long: " << ULONG_MAX << endl;
cout << "unsigned char: " << UCHAR_MAX << endl << endl;
cout << "Minimum values:" << endl;
cout << "int: " << INT_MIN << endl;
cout << "short: " << SHRT_MIN << endl;
cout << "long: " << LONG_MIN <<endl;
cout << "char: " << CHAR_MIN <<endl;
cout << "signed char: " << SCHAR_MIN <<endl;
system("pause");
return 0;
}
way2:
自行通过计算得到 way2:
#include<iostream>
usingnamespacestd;
int_tmain(intargc,_TCHAR*argv[])
{
size_tsz=sizeof(int);
__int64base=1;
__int64range=base<<(sz*8-1);//1位符号位,这里打印出最大值,最小值同理
cout<<range<<endl;
return0;
}
【thinkinnight】:
还有,这里使用__int64来存取,否则会溢出
【steedhorse】:
#include<limits>
#include<iostream>
usingnamespacestd;
template<typenameINT_TYPE>
structto_int{
typedefINT_TYPEint_type;
};
template<>
structto_int<signedchar>{
typedefsignedintint_type;
};
template<>
structto_int<unsignedchar>{
typedefunsignedintint_type;
};
template<typenameINT_TYPE>
voidprint_scope(){
cout<<typeid(INT_TYPE).name()<<":\t";
cout<<(typenameto_int<INT_TYPE>::int_type)numeric_limits<INT_TYPE>::min()<<"-"
<<(typenameto_int<INT_TYPE>::int_type)numeric_limits<INT_TYPE>::max()<<endl;
}
intmain(){
print_scope<signedchar>();
print_scope<unsignedchar>();
print_scope<signedshort>();
print_scope<unsignedshort>();
print_scope<signedint>();
print_scope<unsignedint>();
print_scope<signedlong>();
print_scope<unsignedlong>();
return0;
}