C/C++编程:数值的极值

雨点打透心脏的1/2处 2022-05-17 09:53 254阅读 0赞

C++标准库的极值由template numberic_limits提供,用来取代C的预处理器常量,优点在于:

  • 提供了更好的类型安全性
  • 可以写出一个template以核定这些极值

numberic_limits是一个template,它对所有类型提供了一个通用的解决方案。并且为某些类型提供了一个特化版本

通用型的 numeric_limits 以及其特化版本都被包含在头文件中。 特性化版本包括基础类型:bool, char, signed char, unsigned char, char16_t, char32_t, wchar_t, short, unsigned short, int, unsigned int, long, unsigned long, long long, unsigned long long, float, double, and long double。可以为自定义的数值类型加上一份补充。

numeric_limits<>成员和含义
















































































































成员 含义 对应C常量
is_specialized 是否有极值  
is_signed 带有正负号  
is_integer 整数类型  
is_exact 计算结果不产生舍入误差  
is_bounded 数值集的个数有限  
is_modulo 两正值相加,结果可能溢出而回绕为较小的值  
is_iec559 遵从IEC559及IEEE754标准  
min() 最小有限值 INT_MIN,FLT_MIN,CHAR_MIN,…
max() 最大极值 INT_MAX,FLT_MAX,…
lowest() 最大负有限值  
digits 字符和整数:不含正负号位数 CHAR_BIT
浮点数: radix(见下)的位数  
max_digits10 必要的十进制数位个数  
radix 整数:表述式的底(base),几乎总是2  
浮点数: 指数表达式的底(Base) FLT_RADIX
min_exponent 底radix的最小负整数指数 FLT_MIN_EXP,…
max_exponent 底radix的最大负整数指数 FLT_MAX_EXP,…
min_exponent10 底10的最小负整数指数 FLT_MIN_10_EXP,…
max_exponent10 底10的最大负整数指数 FLT_MAX_10_EXP,…
epsilon() 1和接近1的值之间的差距 FLT_EPSILON,…
round_style 舍入风格  

示例

你可以对任何类型进行询问,无论它是否定义了极值

  1. #include <iostream>
  2. #include <limits>
  3. #include <string>
  4. using namespace std;
  5. int main() {
  6. //对bool使用文本表示
  7. cout << boolalpha;
  8. // print maximum of integral types
  9. cout << "max(short): " << numeric_limits<short>::max() << endl;
  10. cout << "max(int): " << numeric_limits<int>::max() << endl;
  11. cout << "max(long): " << numeric_limits<long>::max() << endl;
  12. cout << endl;
  13. // print maximum of floating-point types
  14. cout << "max(float): "
  15. << numeric_limits<float>::max() << endl;
  16. cout << "max(double): "
  17. << numeric_limits<double>::max() << endl;
  18. cout << "max(long double): "
  19. << numeric_limits<long double>::max() << endl;
  20. cout << endl;
  21. // print whether char is signed
  22. cout << "is_signed(char): "
  23. << numeric_limits<char>::is_signed << endl;
  24. cout << endl;
  25. // print whether numeric limits for type string exist
  26. cout << "is_specialized(string): "
  27. << numeric_limits<string>::is_specialized << endl;
  28. return 0;
  29. }

20210222103932700.png

最后一行显示,string没有定义数值极限。这是当然,因为string并非数值类型

参考:14 Numeric Limits 数值极限

发表评论

表情:
评论列表 (有 0 条评论,254人围观)

还没有评论,来说两句吧...

相关阅读