C++ - std::srand-程序员宅基地

技术标签: srand  C++  std  C++ tmp  

C++ - std::srand

Defined in header <cstdlib> - 定义于头文件 <cstdlib>

1. std::srand

void srand (unsigned int seed);

Initialize random number generator - 初始化伪随机数生成器 (函数)

The pseudo-random number generator is initialized using the argument passed as seed.
伪随机数生成器使用 seed 传递的参数进行初始化。

For every different seed value used in a call to srand, the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand.
对于调用 srand 时使用的每个 seed 值,可以期望伪随机数生成器在随后的 rand 调用中生成不同的结果序列。

Two different initializations with the same seed will generate the same succession of results in subsequent calls to rand.
具有相同 seed 的两个不同的初始化将在随后对 rand 的调用中生成相同的结果序列。

If seed is set to 1, the generator is reinitialized to its initial value and produces the same values as before any call to rand orsrand.
如果将 seed 设置为 1,则将生成器重新初始化为其初始值,并产生与调用 rand orsrand 之前相同的值。

In order to generate random-like numbers, srand is usually initialized to some distinctive runtime value, like the value returned by function time (declared in header <ctime>). This is distinctive enough for most trivial randomization needs.
为了生成类似随机的数字,通常将 srand 初始化为一些独特的运行时值,例如由 time 函数返回的值 (在头文件 <ctime> 中声明)。对于大多数琐碎的随机化需求而言,这足够独特。

Seeds the pseudo-random number generator used by std::rand() with the value seed.
以值 seed 播种 std::rand() 所用的伪随机数生成器。

If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1).
若在任何 srand() 的调用前使用 rand(),则 rand() 表现为如同它被以 srand(1) 播种。

Each time rand() is seeded with the same seed, it must produce the same sequence of values.
每次以同一 seed 播种 rand() 时,它必须产生相同的值数列。

srand() is not guaranteed to be thread-safe.
srand() 不保证为线程安全。

dereference [ˌdiːˈrefrəns]:v. 间接引用,间接访问,解引用
reallocate [ˌriːˈæləkeɪt]:v. 重新分配,再指派

Generally speaking, the pseudo-random number generator should only be seeded once, before any calls to rand(), at the start of the program. It should not be repeatedly seeded, or reseeded every time you wish to generate a new batch of pseudo-random numbers.
通常来说,应该只播种一次伪随机数生成器,在程序开始处,任何到 rand() 的调用前。不应重复播种,或每次希望生成新一批伪随机数时重新播种。

Standard practice is to use the result of a call to time(0) as the seed. However, time() returns a time_t value, and time_t is not guaranteed to be an integral type. In practice, though, every major implementation defines time_t to be an integral type, and this is also what POSIX requires.
标准实践是使用以 time(0) 为种子调用的结果。然而 time() 返回 time_t 值,而不保证 time_t 是整数类型。尽管实践中,主流实现都定义 time_t 为整数类型,且此亦为 POSIX 所要求。

2. Parameters

seed
An integer value to be used as seed by the pseudo-random number generator algorithm.
伪随机数生成器算法将用作种子的整数值。

the seed value (种子值)

3. Return value

none - 无

4. Examples

srand(time(NULL));

使用当前时间进行伪随机数发生器的初始化。
time(NULL) 函数的返回值是作为 srand() 函数的参数。srand(time(NULL)); 以现在的系统时间作为随机数的种子来产生随机数,设置成 NULL 获得系统的当前时间,单位为秒。

4.1 std::srand

//============================================================================
// Name        : std::srand
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <stdio.h>      /* printf, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

int main()
{
	printf("First number: %d\n", rand() % 100);
	srand(time(NULL));
	printf("Random number: %d\n", rand() % 100);
	srand(1);
	printf("Again the first number: %d\n", rand() % 100);

	return 0;
}

Possible output:

First number: 83
Random number: 13
Again the first number: 83

4.2 std::srand

//============================================================================
// Name        : std::srand
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <cstdlib>
#include <iostream>
#include <ctime>

int main()
{
	std::srand(std::time(0)); // use current time as seed for random generator
	int random_variable = std::rand();
	std::cout << "Random value on [0 " << RAND_MAX << "]: " << random_variable << '\n';

	return 0;
}

Possible output:

Random value on [0 2147483647]: 631634451

5. Data races - 数据竞争

The function accesses and modifies internal state objects, which may cause data races with concurrent calls to rand or srand.
该函数访问和修改内部状态对象,这可能导致并发调用 rand or srand 的数据竞争。

Some libraries provide an alternative function of rand that explicitly avoids this kind of data race: rand_r (non-portable).
一些库提供了 rand 的替代功能,它明确避免了这种数据竞争:rand_r (不可移植)。

C++ library implementations are allowed to guarantee no data races for calling this function.
允许 C++ 库实现来保证调用此函数不会发生数据竞争。

6. Exception safety - 异常安全性

No-throw guarantee: this function never throws exceptions.
无抛出保证:此函数从不抛出异常。

assignment [ə'saɪnmənt]:n. 任务,布置,赋值

References

http://www.cplusplus.com/reference/cstdlib/srand/
https://en.cppreference.com/w/cpp/numeric/random/srand

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/chengyq116/article/details/104429546

智能推荐

倍福PLC控制台达EtherCAT伺服案例分析_台达伺服ethercat设置-程序员宅基地

文章浏览阅读3.1k次。软件 :Twincat V2.11.2249(最新 Twincat2 安装包下载路径ftp://ftp.beckhoff.com.cn/TwinCAT2/install/2.11%20R3/)硬件 :C6640‐0030 工控机 、ASDA A2‐E (台达 Ethercat 伺服驱动器)XML 文件 :ASDA2‐E rev3.33.xml配置文件 :DELTA.tsmPLC 文件 :DELTA_PLC.proXML 文件下载XML 文件可以在台达官网下载;XML 文_台达伺服ethercat设置

1043:整数大小比较_问题 2503: 整数大小比较-程序员宅基地

文章浏览阅读1.5k次。#include &amp;amp;lt;stdio.h&amp;amp;gt;int main (){ long long int a,b; scanf(&amp;quot;%lld %lld&amp;quot;,&amp;amp;amp;a,&amp;amp;amp;b); if(a&amp;amp;gt;b) { printf(&amp;quot;&amp;amp;gt;&amp;quot;); } el_问题 2503: 整数大小比较

linux达梦数据库安装步骤_linux 达梦 client 下载安装-程序员宅基地

文章浏览阅读5.6w次,点赞8次,收藏93次。下载最新linux版本的达梦V7.1.5.178-Build(2017.04.24-80034) Windows版本:http://product.dameng.com/zt/download/dm7_win64.zipLinux版本:http://product.dameng.com/zt/download/dm7_neoky6_64.tar.gz都下载下来,server安装到lin_linux 达梦 client 下载安装

The type WebMvcConfigurerAdapter is deprecated 两种解决方式_webmvcconfigureradapter不能用了-程序员宅基地

文章浏览阅读3.8k次,点赞2次,收藏7次。WebMvcConfigurerAdapter类被弃用后的两种选择介绍在本文中,将介绍将spring 4.xx(或者更低)版本升级到Spring 5.xx以及将Spring Boot 1.xx版本升级到Spring Boot 2.xx版本后会报的一个严重警告:“Warning:The type WebMvcConfigurerAdapter is deprecated.” ,以及快速的分析产生..._webmvcconfigureradapter不能用了

内存溢出和内存泄漏的区别、产生原因以及解决方案_内存溢出和内存泄漏的区别?哪些情况下会产生内存泄漏?-程序员宅基地

文章浏览阅读4.2k次,点赞4次,收藏13次。内存溢出 out of memory,是指程序在申请内存时,没有足够的内存空间供其使用,出现out of memory;比如申请了一个integer,但给它存了long才能存下的数,那就是内存溢出。内存泄露 memory leak,是指程序在申请内存后,无法释放已申请的内存空间,一次内存泄露危害可以忽略,但内存泄露堆积后果很严重,无论多少内存,迟早会被占光。memory leak会最终会导致out of memory!内存溢出就是你要求分配的内存超出了系统能给你的,系统不能满足需求,于是产生溢出。内_内存溢出和内存泄漏的区别?哪些情况下会产生内存泄漏?

W32Dasm反编译教程+工具_w32dsm-程序员宅基地

文章浏览阅读2k次。这里写自定义目录标题欢迎使用Markdown编辑器新的改变功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章UML 图表FLowchart流程图导出与导入导出导入给大家转一个..._w32dsm

随便推点

飞凌iMX8MM扩展HDMI和LVDS显示 硬件设计原理图_飞凌内核加载lvds-程序员宅基地

文章浏览阅读611次。FETMX8MM-C核心板基于NXP公司iMX8MMini 四核64位处理器设计,主频最高1.8GHz,Cortex-A53架构;2GB DDR4 RAM,支持一个通用型Cortex-M4400MHz内核处理器。可提供多种音频接口,包括I2S、AC97、TDM、PDM和SPDIF。提供多种外设接口,如MIPI-CSI、MIPI-DSI、USB、PCIe、UART、eCSPI、IIC和千兆以太网。飞凌iMX8MM核心板具备1080p 60Hz的H.265和VP9解码器; 相比传统的H.264编码,平均解.._飞凌内核加载lvds

G1GC技术资料_attempting to trigger g1gc due to high heap usage-程序员宅基地

文章浏览阅读203次。网址1:https://www.oracle.com/technical-resources/articles/java/g1gc.htmlLearn about how to adapt and tune the G1 GC for evaluation, analysis and performance.TheGarbage First Garbage Collector (G1 G..._attempting to trigger g1gc due to high heap usage

Android之Fragment与Activity的那些事儿_activity fragment onsaveinstance-程序员宅基地

文章浏览阅读564次。一:Fragment我们需要知道的一点: 所有的Fragment子类都必须包含一个公共的空的构造器。因为在需要的时候,Framework会经常重新实例化Fragment类,在特殊的状态恢复期间,需要能够找到这个构造器来实例化Fragment类。如果空的构造器无效,那么在状态恢复期间会导致运行时异常发生。所以对于Fragment创建实例的传参操作,官方推荐用setArguments来传递参数,而不要_activity fragment onsaveinstance

python2.7 中 print()函数的使用及input()、与raw_input()的区别_python 2.7 input-程序员宅基地

文章浏览阅读2.2k次。一、python2.7 中 print()函数的使用:直接输出双引号或单引号内的任何字符或数字输出变量的值,不用加双引号或单引号,直接在()内写变量名称即可,或者print后面空格直接写变量名称同时输出多项内容,不同内容用逗号隔开,不同内容包括双引号或单引号内的内容、变量。在双引号或单引号内的内容中掺杂有一个变量或多个,在要输出变量值的位置用%加变量类型来代替,比如字符型%s,浮点型%f。并在双引号或单引号后面再加一个%号和括号,并在括号内按顺序写入变量名,变量之间用逗号隔开。字符串格式化输出:_python 2.7 input

DDR的基本原理_non target odt-程序员宅基地

文章浏览阅读2.8k次。一、 软件平台与硬件平台  软件平台:    1、操作系统:Windows-8.1    2、开发套件:无    3、仿真工具:无  硬件平台:    1、 FPGA型号:无    2、 DDR3型号:无二、 存储器的分类  存储器一般来说可以分为内部存储器(内存),外部存储器(外存),缓冲存储器(缓存)以及闪存这几个大类。内存也称为主存储器,位于系统主机板上,可以同CPU直接进行信息交换。其主要特点是:运行速度快,容量小。外存也称为辅助存储器,不能与CPU之间直接进行信息交..._non target odt

DP和HDMI区别_dp hdmi-程序员宅基地

文章浏览阅读1.2w次,点赞2次,收藏34次。转自:https://www.toutiao.com/i6877677362054595080在目前市面上显示器接口中,VGA和DVI已经逐渐退出了历史舞台,Type-C还算是小众,而DP(DisplayPort)与HDMI则成为了主流产品的标配,目前的主流级显卡也是以这两个输出接口为主,而新的问题也随之诞生了:当这两个接口都可以使用的时候,选择哪个会更好?对于大部分普通的消费者来说,显示器能跟主机正常连接就行,随便哪个接口都无所谓,反正能正常使用,但是对于DIY玩家来说,这个问题就显得非常重要_dp hdmi

推荐文章

热门文章

相关标签