跳到主要内容

C++ srand() 函数

C++ 中的 srand() 函数为 rand() 函数使用的伪随机数生成器设置种子。它定义在 cstdlib 头文件中。

示例

#include<iostream>
#include<cstdlib>
using namespace std;

int main() {

// 将种子设置为 10
srand(10);

// 生成随机数
int random = rand();

cout << random;

return 0;
}

// 输出:71

srand() 语法

srand() 的语法是:

srand(unsigned int seed);

srand() 参数

srand() 函数接受以下参数:

  • seed - 一个类型为 unsigned int 的种子值

srand() 返回值

srand() 函数不返回任何值。

srand() 原型

定义在 cstdlib 头文件中的 srand() 原型是:

void srand(unsigned int seed);

这里,srand() 参数 seedrand() 函数用作种子。

C++ srand() 的工作原理

srand() 函数为 rand() 函数设置种子。rand() 函数的默认种子是 1

这意味着,如果在 rand() 之前没有调用 srand()rand() 函数的行为就好像它是用 srand(1) 种子的。

然而,如果在 rand 之前调用了 srand() 函数,那么 rand() 函数将使用 srand() 设置的种子生成一个数字。

注意: “种子”是伪随机数序列的起点。要了解更多,请访问 StackOverflow 中的链接。

示例 1:C++ srand()

#include<iostream>
#include<cstdlib>
using namespace std;

int main() {
int random = rand();

// srand() 尚未被调用,所以种子 = 1
cout << "种子 = 1, 随机数 = " << random << endl;

// 将种子设置为 5
srand(5);

// 生成随机数
random = rand();
cout << "种子 = 5, 随机数 = " << random << endl;

return 0;
}

输出

种子 = 1, 随机数 = 41
种子 = 5, 随机数 = 54

srand() 的标准实践

  1. 伪随机数生成器不应该在我们每次生成一组新数字时都重新种子,而应该在程序开始时只种子一次,在任何 rand() 调用之前。
  2. 最好使用 time(0) 调用的结果作为种子。time() 函数返回自 1970年1月1日 00:00时 UTC 以来的秒数(即当前的 Unix 时间戳)。

因此,种子值随时间变化。所以每次我们运行程序时,都会生成一组新的随机数。

示例 2:srand() 与 time() 结合使用

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;

int main() {

// 将种子设置为 time(0)
srand(time(0));

// 生成随机数
int random = rand();

// 打印种子和随机数
cout << "种子 = " << time(0) << endl;
cout << "随机数 = " << random;

return 0;
}

输出

种子 = 1629892833
随机数 = 5202