c++中如何返回内置类型的最值——使用

c++中如何返回内置类型的最值——<limits>使用

在c++的<limits>中定义了如下的一个模板类:

template<class Type> class numeric_limits


它可以求出下列内置类型的一些特性:
wchar_t, bool, char, signed char, unsigned char, short, unsigned short, 
int, unsigned int, long, unsigned long, float, double, and long double.

有这么四个函数,比较有用:
max() Returns the maximum finite value for a type.


min() Returns the minimum normalized value for a type.

digits()   Returns the number of radix digits that the type can represent without loss of precision.

digits10()   Returns the number of decimal digits that the type can represent without loss of precision.

max()举例如下:msdn2005上的例子

// numeric_limits_max.cpp
#include <iostream>
#include <limits>

using namespace std;

int main() {
   cout << "The maximum value for type float is: "
        << numeric_limits<float>::max( )
        << endl;
   cout << "The maximum value for type double is: "
        << numeric_limits<double>::max( )
        << endl;
   cout << "The maximum value for type int is: "
        << numeric_limits<int>::max( )
        << endl;
   cout << "The maximum value for type short int is: "
        << numeric_limits<short int>::max( )
        << endl;
}

Output

The maximum value for type float is: 3.40282e+038
The maximum value for type double is: 1.79769e+308
The maximum value for type int is: 2147483647
The maximum value for type short int is: 32767

digits()举例:
// numeric_limits_digits_min.cpp
#include <iostream>
#include <limits>

using namespace std;

int main( )
{
   cout << numeric_limits<float>::digits <<endl;
   cout << numeric_limits<double>::digits <<endl;
   cout << numeric_limits<long double>::digits <<endl;
   cout << numeric_limits<int>::digits <<endl;
   cout << numeric_limits<__int64>::digits <<endl;
}

Output

24
53
53
31
63

digits10举例:
// numeric_limits_digits10.cpp
#include <iostream>
#include <limits>

using namespace std;

int main( )
{
   cout << numeric_limits<float>::digits10 <<endl;
   cout << numeric_limits<double>::digits10 <<endl;
   cout << numeric_limits<long double>::digits10 <<endl;
   cout << numeric_limits<int>::digits10 <<endl;
   cout << numeric_limits<__int64>::digits10 <<endl;
}

Output

6
15
15
9
18

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值