C++ numeric_limits的用法

1. numeric_limits是什么?

一般来说,数值型别的极值是一个与平台相关的特性。C++标准程序库通过template numeric_limits提供这些极值,取代传统C语言,所采用的预处理常数。新的极值概念有两个优点,第一是提供更好的型别安全性,第二是程序员可借此写出一些template以核定这些极值。

2. 小例展示numeric_limits的基本用法:

#include <limits>  
#include <iostream>  
using namespace std;  
  
int main() {  
    cout << boolalpha;  
  
    cout << "max(short): " << numeric_limits<short>::max() << endl;  
    cout << "min(short): " << numeric_limits<short>::min() << endl;  
  
    cout << "max(int): " << numeric_limits<int>::max() << endl;  
    cout << "min(int): " << numeric_limits<int>::min() << endl;  
  
    cout << "max(long): " << numeric_limits<long>::max() << endl;  
    cout << "min(long): " << numeric_limits<long>::min() << endl;  
  
    cout << endl;  
  
    cout << "max(float): " << numeric_limits<float>::max() << endl;  
    cout << "min(float): " << numeric_limits<float>::min() << endl;  
  
    cout << "max(double): " << numeric_limits<double>::max() << endl;  
    cout << "min(double): " << numeric_limits<double>::min() << endl;  
  
    cout << "max(long double): " << numeric_limits<long double>::max() << endl;  
    cout << "min(long double): " << numeric_limits<long double>::min() << endl;  
  
    cout << endl;  
  
    cout << "is_signed(char): "  
        << numeric_limits<char>::is_signed << endl;  
    cout << "is_specialized(string): "   
        << numeric_limits<string>::is_specialized << endl;  
}

我机器上的运行结果:

max(short): 32767  

min(short): -32768  

max(int): 2147483647  

min(int): -2147483648  

max(long): 2147483647  

min(long): -2147483648  

max(float): 3.40282e+038  

min(float): 1.17549e-038  

max(double): 1.79769e+308  

min(double): 2.22507e-308  

max(long double): 1.79769e+308  

min(long double): 2.22507e-308  

is_signed(char): true  

is_specialized(string): false  

请按任意键继续. . .  

转载于:https://my.oschina.net/shou1156226/blog/743318

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值