首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

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

2012-02-17 
请编写一个c程序确定signed,unsigned的char,short,int和long变量取值范围way1:通过打印标准的头文件中的相

请编写一个c程序确定signed,unsigned的char,short,int和long变量取值范围
way1:
通过打印标准的头文件中的相应的值来完成

way2:
自行通过计算得到

麻烦谁能给出代码?

[解决办法]
signed int的范围,其他和这个差不多。
way1:
#include <climits>
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
cout < <INT_MAX < <endl;
cout < <INT_MIN < <endl;
return 0;
}

way2:

#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
size_t sz = sizeof(int);
__int64 base = 1;
__int64 range = base < <(sz*8-1); //1位符号位,这里打印出最大值,最小值同理
cout < <range < <endl;
return 0;
}

[解决办法]
#include <limits>
#include <iostream>
using namespace std;

template <typename INT_TYPE>
struct to_int {
typedef INT_TYPE int_type;
};

template <>
struct to_int <signed char> {
typedef signed int int_type;
};

template <>
struct to_int <unsigned char> {
typedef unsigned int int_type;
};

template <typename INT_TYPE>
void print_scope() {
cout < < typeid(INT_TYPE).name() < < ":\t ";
cout < < (typename to_int <INT_TYPE> ::int_type)numeric_limits <INT_TYPE> ::min() < < " - "
< < (typename to_int <INT_TYPE> ::int_type)numeric_limits <INT_TYPE> ::max() < < endl;
}

int main() {
print_scope <signed char> ();
print_scope <unsigned char> ();
print_scope <signed short> ();
print_scope <unsigned short> ();
print_scope <signed int> ();
print_scope <unsigned int> ();
print_scope <signed long> ();
print_scope <unsigned long> ();

return 0;
}

热点排行