srand()、rand()
srand(static_cast<unsigned int>(time(nullptr)))
是 C++ 中用于初始化随机数生成器(Random Number Generator, RNG)的一个常用语句。srand
函数是 C++ 标准库 <cstdlib>
中的一部分,用于设置随机数发生器的种子值,这个种子值是后续随机数生成的基础。
static_cast<unsigned int>(time(nullptr))
部分的作用是:
time(nullptr)
函数会返回当前时间(以秒为单位)自 1970 年 1 月 1 日 00:00:00 UTC 的时间戳。nullptr
表示使用当前进程的时间。static_cast<unsigned int>()
进行类型转换,将time_t
类型(通常是一个整数)转换成无符号的unsigned int
类型。这是因为在srand
函数中,种子值通常需要是整数类型。
整体来说,这个表达式用当前时间作为随机数生成器的初始种子,确保每次程序运行时得到不同的随机数序列。每次调用rand()
或srand()
后,随机数生成器的状态就会不同,从而得到不同的一系列随机数。如果在程序的生命周期内不改变种子,那么每次程序启动时都会得到相同的随机数序列。
#include <bits/stdc++.h>
using namespace std;
const int Row = 2;
const int Col = 4;
int main()
{
srand(static_cast<unsigned int>(time(nullptr)));
string array[Row][Col] = {
{"安阳", "滑县", "林州", "内黄"},
{"支农", "就业", "帮扶", "林业"}
};
int a = rand() % Col;
int b = rand() % Col;
cout << array[0][a] << array[1][b];
return 0;
}