C/C++编程:数值的极值
C++标准库的极值由template numberic_limits提供,用来取代C的预处理器常量,优点在于:
- 提供了更好的类型安全性
- 可以写出一个template以核定这些极值
numberic_limits是一个template,它对所有类型提供了一个通用的解决方案。并且为某些类型提供了一个特化版本
通用型的 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 | 舍入风格 |
示例
你可以对任何类型进行询问,无论它是否定义了极值
#include <iostream>
#include <limits>
#include <string>
using namespace std;
int main() {
//对bool使用文本表示
cout << boolalpha;
// print maximum of integral types
cout << "max(short): " << numeric_limits<short>::max() << endl;
cout << "max(int): " << numeric_limits<int>::max() << endl;
cout << "max(long): " << numeric_limits<long>::max() << endl;
cout << endl;
// print maximum of floating-point types
cout << "max(float): "
<< numeric_limits<float>::max() << endl;
cout << "max(double): "
<< numeric_limits<double>::max() << endl;
cout << "max(long double): "
<< numeric_limits<long double>::max() << endl;
cout << endl;
// print whether char is signed
cout << "is_signed(char): "
<< numeric_limits<char>::is_signed << endl;
cout << endl;
// print whether numeric limits for type string exist
cout << "is_specialized(string): "
<< numeric_limits<string>::is_specialized << endl;
return 0;
}
最后一行显示,string没有定义数值极限。这是当然,因为string并非数值类型
参考:14 Numeric Limits 数值极限
还没有评论,来说两句吧...