Skip to content

标准C++中获取某种数据类型的最大值和最小值

用惯C#,比如我想让一个int数等于无穷大,只需要简单写:

int a = int.MaxValue;

转到C++上,疑惑了... 首先C++不会有属性这种东西,而且不同平台上的某个类型的最大最小值是不一样的。 解决方案是使用limits头文件的方法。

#include <limits>
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    cout<<"short:"<<endl;
    cout<<"min="<<numeric_limits<short>::min()<<endl;
    cout<<"max="<<numeric_limits<short>::max()<<endl;

    cout<<"int:"<<endl;
    cout<<"min="<<numeric_limits<int>::min()<<endl;
    cout<<"max="<<numeric_limits<int>::max()<<endl;

    cout<<"double:"<<endl;
    cout<<"min="<<numeric_limits<double>::min()<<endl;
    cout<<"max="<<numeric_limits<double>::max()<<endl;

    cout<<"long:"<<endl;
    cout<<"min="<<numeric_limits<long>::min()<<endl;
    cout<<"max="<<numeric_limits<long>::max()<<endl;
    return 0;
}

在我的工作站平台(Microsoft (R) Windows (R) Resource Compiler Version 6.1.6723.1)下输出:

short:
min=-32768
max=32767
int:
min=-2147483648
max=2147483647
double:
min=2.22507e-308
max=1.79769e+308
long:
min=-2147483648
max=2147483647

在Ubuntu Server下用gcc version 4.2.4执行的结果如下

short:
min=-32768
max=32767
int:
min=-2147483648
max=2147483647
double:
min=2.22507e-308
max=1.79769e+308
long:
min=-2147483648
max=2147483647