700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 请编写一个c程序确定signed unsigned的char short int和long变量取值范围

请编写一个c程序确定signed unsigned的char short int和long变量取值范围

时间:2022-11-09 05:18:09

相关推荐

请编写一个c程序确定signed unsigned的char short int和long变量取值范围

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;

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。