请编写一个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;
}