C++基础::<limits>

#include <limits>

numeric_limits <int>

我们常讲,int:是有符号整型,而 unsigned int:是无符号整型,可此话怎讲呢,自然是值域(range),也即数值范围不同。

std::cout << std::numeric_limits <unsigned int>::min() << std::endl;
                                // 0
std::cout << std::numeric_limits<unsigned int>::max() << std::endl;
                        // 4294967295
                        // 4294967295的二进制恰为:
                        // 1111 1111 1111 1111 1111 1111 1111 1111 == 2^32-1                    

也即 unsigned int 的取值范围为: [0,2 32 1] 

我们再来看 int的取值范围(最高位,也即第32位为符号位):

std::cout << std::numeric_limits<int>::min() << std::endl;
                        // -2147483648
                        // 也即2^31,第32位为1,其余各位均为0
std::cout << std::numeric_limits<int>::max() << std::endl;
                        // 22147483647
                        // 2^31-1

故 int 的取值范围为: [2047483648,2047483647] 

numeric_limits <double>

std::cout << std::numeric_limits<double>::min() << std::endl;
                            // 2.22507e-308
std::cout << std::numeric_limits<double>::max() << std::endl;
                            // 1.79769e+308

注意这里的 std::numeric_limits<double>::min() 表达不是   ,而是(正)无穷小量 ϵ 

如果我们想要表达负无穷(   ),我们自然可以使用:

std::cout << -std::numeric_limits<double>::max() << std::endl;
                            // -1.79769e+308

std::numeric_limits<T>::epsilon()

注意这里:

std::cout << std::numeric_limits<double>::min() << std::endl;
                            // 2.22507e-308
std::cout << std::numeric_limits<double>::epsilon() << std::endl;
                            // 2.22045e-016

两者显然不在一个数量级上。
我们来看 msdn 对epsilon的说明:

The function returns the difference between 1 and the smallest value greater than 1 that is representable for the data type.

也即 std::numeric_limits<T>::epsilon() 返回的是计算机体系结构所能判断的两个同类型的数据是否相等的极限,也即如果两个数的差值小于std::numeric_limits<T>::epsilon() ,在计算机看来两者没差。

std::cout << std::boolalpha;
std::cout << (1. == 1.+std::numeric_limits<double>::epsilon()) << std::endl;
                                // false
std::cout << (1. == 1.+std::numeric_limits<double>::epsilon()/2) << std::endl;
                                // true

应用

用最大值(max,取值范围的极限)表示该值未取值

#define NULL_INT std::numeric_limits<int>::max()
#define NULL_SIZE std::numeric_limits<unsigned int>::max()
#define NULL_REAL std::numeric_limits<double>::max()
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五道口纳什

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值