<limits>包含所有标准数据类型的上下限信息
numeric_limit<类型名>::min(), max() , digits
min()整型和浮点数类型最小值含义不同,整型会得到真正的最小值,即带符号的负数
对于浮点数类型返回可以存储的最小正数
digits返回二进制数字位数,带符号的整数类型,返回除符号位之外的二进制数字的位数
对于浮点数类型返回尾数钟二进制数字的位数
digits10返回十进制数字位数,带符号的整数类型,返回除符号位之外的十进制数字的位数
对于浮点数类型返回尾数中十进制数字的位数
// Program 3.3 Finding maximum and minimum values for data types
#include <limits>
#include <iostream>
using std::cout;
using std::endl;
using std::numeric_limits;
int main() {
cout << endl
<< "The range for type short is from "
<< numeric_limits<short>::min()
<< " to "
<< numeric_limits<short>::max();
cout << endl << numeric_limits<short>::digits;
cout << endl << numeric_limits<short>::digits10;
cout << endl
<< "The range for type int is from "
<< numeric_limits<int>::min()
<< " to "
<< numeric_limits<int>::max();
cout << endl << numeric_limits<int>::digits;
cout << endl << numeric_limits<int>::digits10;
cout << endl
<< "The range for type long is from "
<< numeric_limits<long>::min()
<< " to "
<< numeric_limits<long>::max();
cout << endl << numeric_limits<long>::digits;
cout << endl << numeric_limits<long>::digits10;
cout << endl
<< "The range for type float is from "
<< numeric_limits<float>::min()
<< " to "
<< numeric_limits<float>::max();
cout << endl << numeric_limits<float>::digits;
cout << endl << numeric_limits<float>::digits10;
cout << endl
<< "The range for type double is from "
<< numeric_limits<double>::min()
<< " to "
<< numeric_limits<double>::max();
cout << endl << numeric_limits<double>::digits;
cout << endl << numeric_limits<double>::digits10;
cout << endl
<< "The range for type long double is from "
<< numeric_limits<long double>::min()
<< " to "
<< numeric_limits<long double>::max();
cout << endl << numeric_limits<long double>::digits;
cout << endl << numeric_limits<long double>::digits10;
cout << endl;
return 0;
}
以下代码使用了unsigned char且采用do...while形式
for(unsigned char ch=0;ch<=std::numeric_limits<unsigned char>::max();ch++) //不能使用这种形式,因为ch等于最大值时,加1后下一个值为0,是个死循环
// Program 5.9 Using the continue statement #include <iostream> #include <iomanip> #include <cctype> #include <limits> using std::cout; using std::endl; using std::setw; int main() { // Output the column headings cout << endl << setw(13) << "Character " << setw(13) << "Hexadecimal " << setw(13) << "Decimal " << endl; cout << std::uppercase; // Uppercase hex digits unsigned char ch = 0; // Character code // Output characters and corresponding codes do { if(!std::isprint(ch)) // If it does not print continue; // skip this iteration cout << setw(7) << ch << std::hex // Hexadecimal mode << setw(13) << static_cast<int>(ch) << std::dec // Decimal mode << setw(13) << static_cast<int>(ch) << endl; } while(ch++ < std::numeric_limits<unsigned char>::max()); return 0; }