C++ 中的 INT_MAX 和 INT_MIN 宏表达式
本文将演示有关如何在 C++ 中利用 INT_MAX 和 INT_MIN 宏表达式的多种方法。
使用 INT_MIN
和 INT_MAX
来访问 C++ 中特定于类型的限制
C++ 语言定义了多种内置数据类型,并规定了它们应占用多少内存以及相应的最大/最小值。像整数这样的数据类型通常用于需要考虑其可能出现的最大值和最小值的计算中。尽管限制取决于特定类型的存储大小,但这些限制会根据硬件平台而有所不同。因此,我们需要使用固定的句柄访问这些值,因此需要使用宏表达式 INT_MIN
和 INT_MAX
。这些对应于 signed int
数据类型的最小值和最大值。下面的示例演示了 <climits>
头文件下可用的多个宏表达式。
#include <iostream>
#include <climits>
int main() {
printf("CHAR_BIT = %d\n", CHAR_BIT);
printf("MB_LEN_MAX = %d\n", MB_LEN_MAX);
printf("\n");
printf("CHAR_MIN = %+d\n", CHAR_MIN);
printf("CHAR_MAX = %+d\n", CHAR_MAX);
printf("SCHAR_MIN = %+d\n", SCHAR_MIN);
printf("SCHAR_MAX = %+d\n", SCHAR_MAX);
printf("UCHAR_MAX = %u\n", UCHAR_MAX);
printf("\n");
printf("SHRT_MIN = %+d\n", SHRT_MIN);
printf("SHRT_MAX = %+d\n", SHRT_MAX);
printf("USHRT_MAX = %u\n", USHRT_MAX);
printf("\n");
printf("INT_MIN = %+d\n", INT_MIN);
printf("INT_MAX = %+d\n", INT_MAX);
printf("UINT_MAX = %u\n", UINT_MAX);
printf("\n");
printf("LONG_MIN = %+ld\n", LONG_MIN);
printf("LONG_MAX = %+ld\n", LONG_MAX);
printf("ULONG_MAX = %lu\n", ULONG_MAX);
printf("\n");
printf("LLONG_MIN = %+lld\n", LLONG_MIN);
printf("LLONG_MAX = %+lld\n", LLONG_MAX);
printf("ULLONG_MAX = %llu\n", ULLONG_MAX);
printf("\n");
return EXIT_SUCCESS;
}
输出:
CHAR_BIT = 8
MB_LEN_MAX = 16
CHAR_MIN = -128
CHAR_MAX = +127
SCHAR_MIN = -128
SCHAR_MAX = +127
UCHAR_MAX = 255
SHRT_MIN = -32768
SHRT_MAX = +32767
USHRT_MAX = 65535
INT_MIN = -2147483648
INT_MAX = +2147483647
UINT_MAX = 4294967295
LONG_MIN = -9223372036854775808
LONG_MAX = +9223372036854775807
ULONG_MAX = 18446744073709551615
LLONG_MIN = -9223372036854775808
LLONG_MAX = +9223372036854775807
ULLONG_MAX = 18446744073709551615
使用 INT_MIN
和 INT_MAX
在 C++ 中生成随机数
随机数通常是在某个固定范围之间生成的。具有数字数据类型限制以相应地指定范围参数,并且不会溢出生成的结果,这很有用。以下示例代码利用 uniform_int_distribution
来限制所生成数字的范围。在这种情况下,我们指定了 INT_MAX
和 INT_MIN
值以从最大可用范围中检索整数。
#include <iostream>
#include <climits>
#include <random>
#include <iomanip>
using std::cout;
using std::endl;
using std::setprecision;
int main() {
std::random_device rd;
std::default_random_engine eng(rd());
std::uniform_int_distribution<int> distr(INT_MIN, INT_MAX);
for (int n = 0; n < 6; ++n) {
cout << distr(eng) << "\n";
}
cout << endl;
return EXIT_SUCCESS;
}
-895078088
1662821310
-636757160
1830410618
1031005518
-438660615
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn