C / C++ function - rand

Defined in header <stdlib.h>

int rand (void);

0. 产生一定范围内的随机数

产生 [a, b) 的随机整数,使用 (rand() % (b - a)) + a;
[0, (b - a) - 1] + a = [a, (b - 1)] = [a, b)
产生 [a, b] 的随机整数,使用 (rand() % (b - a + 1)) + a;
[0, (b - a + 1) - 1] + a = [0, (b - a)] + a = [a, b]
产生 (a, b] 的随机整数,使用 (rand() % (b - a)) + a + 1;
[0, (b - a) - 1] + a + 1 = [0, (b - a - 1)] + a + 1 = [a + 1, b] = (a, b]

产生 0~1 之间的浮点数,可以使用 rand() / double(RAND_MAX)

1. Generate random number

Returns a pseudo-random integral number in the range between 0 and RAND_MAX (0 and RAND_MAX included).
返回介于 0RAND_MAX 之间的伪随机整数 (包含 0RAND_MAX)。
RAND_MAX 是一个常量,它的默认值在不同的实现中会有所不同,但是值至少是 32767

This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using function srand.
该数字是由一种算法生成的,该算法每次调用时都会返回一个看起来不相关的数字序列。该算法使用种子来生成序列,应使用函数 srand 将其初始化为一些独特的值。

RAND_MAX is a constant defined in <cstdlib>.

srand() seeds the pseudo-random number generator used by rand(). If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1). Each time rand() is seeded with srand(), it must produce the same sequence of values.
srand() 播种 rand() 所用的伪随机数生成器。若在任何对 srand() 的调用前使用 rand(),则 rand() 表现如同它以 srand(1) 播种。每次以 srand() 播种 rand() 时,它必须产生相同的值数列。

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

A typical way to generate trivial pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range:
使用 rand 生成确定范围内的伪随机数的典型方法是:对返回值取模值并加上初始值。

v1 = rand() % 100;         // v1 in the range 0 to 99 = [0, 99]
v2 = rand() % 100 + 1;     // v2 in the range 1 to 100 = [0, 99] + 1 = [1, 100]
v3 = rand() % 30 + 1985;   // v3 in the range 1985 - 2014  = [0, 29] + 1985 = [1985, 2014]
v4 = rand() % 200 + 1;     // [0, 199] + 1 = [1, 200]

Notice though that this modulo operation does not generate uniformly distributed random numbers in the span (since in most cases this operation makes lower numbers slightly more likely).
请注意,此模运算不会在跨度范围中生成均匀分布的随机数 (因为在大多数情况下,此运算使较小的数字更有可能出现)。

C++ supports a wide range of powerful tools to generate random and pseudo-random numbers (see <random> for more info).
C++ 支持各种强大的工具来生成随机和伪随机数 (有关更多信息,请参见 <random>)。

2. Parameters

(none)

3. Return Value

An integer value between 0 and RAND_MAX.
0RAND_MAX 间包含边界的随机整数值。

4. Example

4.1 Example

//============================================================================
// Name        : Yongqiang Cheng
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif/* rand example: guess the number */
#include <stdio.h>      /* printf, scanf, puts, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */int main()
{int Secret, Guess;/* initialize random seed: */srand(time(NULL));/* generate secret number between 1 and 10: */Secret = rand() % 10 + 1;do {printf("Guess the number (1 to 10): ");scanf("%d", &Guess);if (Secret < Guess) puts("The secret number is lower");else if (Secret > Guess) puts("The secret number is higher");} while (Secret != Guess);puts("Congratulations!");return 0;
}

In this example, the random seed is initialized to a value representing the current time (calling time) to generate a different value every time the program is run.
在这个例子中,随机种子被初始化为代表当前时间的值 (称为 time),以在每次程序运行时产生一个不同的值。

Possible output:

Guess the number (1 to 10): 9
The secret number is lower
Guess the number (1 to 10): 5
The secret number is higher
Guess the number (1 to 10): 6
The secret number is higher
Guess the number (1 to 10): 7
The secret number is higher
Guess the number (1 to 10): 8
Congratulations!
请按任意键继续. . .

4.2 Example

//============================================================================
// Name        : Yongqiang Cheng
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif/* rand example: guess the number */
#include <stdio.h>      /* printf, scanf, puts, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */int main(void)
{srand(time(NULL)); //use current time as seed for random generatorint random_variable = rand();printf("Random value on [0,%d]: %d\n", RAND_MAX, random_variable);
}
Random value on [0,32767]: 12901
请按任意键继续. . .

4.3 Example

//============================================================================
// Name        : Yongqiang Cheng
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif/* rand example: guess the number */
#include <stdio.h>      /* printf, scanf, puts, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */int main(void)
{srand((unsigned int)time(NULL)); //use current time as seed for random generatorconst int random_variable = rand();printf("Random value on [0, %d]: %d\n", RAND_MAX, random_variable);const int n = 16;/* 输出 0 到 49 之间的 16 个随机数 */for (int i = 0; i < n; ++i) {printf("%d ", rand() % 50);}printf("\n");return(0);
}
Random value on [0, 32767]: 20719
28 16 33 2 4 17 29 32 21 17 29 27 45 15 21 2
请按任意键继续. . .

4.4 Example - 生成随机数数组

//============================================================================
// Name        : Yongqiang Cheng
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif/* rand example: guess the number */
#include <stdio.h>      /* printf, scanf, puts, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time *//* 输出 1 到 50 之间的 n 个随机数 */
int random_number_generator(int *number_array, const int n)
{for (int i = 0; i < n; ++i) {number_array[i] = rand() % 50 + 1;}return 0;
}int main(void)
{srand((unsigned int)time(NULL)); // use current time as seed for random generatorconst int random_variable = rand();printf("Random value on [0, %d]: %d\n", RAND_MAX, random_variable);const int n = 16;/* 输出 0 到 49 之间的 16 个随机数 */for (int i = 0; i < n; ++i) {printf("%d ", rand() % 50);}printf("\n");const int num = 10;int number_array[num] = { 0 };int ret = random_number_generator(number_array, num);/* 输出 1 到 50 之间的 10 个随机数 */for (int i = 0; i < num; ++i) {printf("%d ", number_array[i]);}printf("\n");return(0);
}
Random value on [0, 32767]: 26738
19 44 16 23 7 14 13 39 10 19 3 15 34 39 22 19
31 6 12 48 49 34 41 17 8 10
请按任意键继续. . .

5. Compatibility

In C, the generation algorithm used by rand is guaranteed to only be advanced by calls to this function. In C++, this constraint is relaxed, and a library implementation is allowed to advance the generator on other circumstances (such as calls to elements of <random>).
在 C 语言中,只能通过调用此函数来保证 rand 使用的生成算法。在 C++ 中,此约束得到了放松,a library implementation is allowed to advance the generator on other circumstances (例如,对 <random> 元素的调用)。

6. Data races

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

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

C++ library implementations are allowed to guarantee no data races for calling this function.
允许 C++ 库实现保证不存在调用该函数的数据竞争。

There are no guarantees as to the quality of the random sequence produced. In the past, some implementations of rand() have had serious shortcomings in the randomness, distribution and period of the sequence produced (in one well-known example, the low-order bit simply alternated between 1 and 0 between calls). rand() is not recommended for serious random-number generation needs, like cryptography.
无对产生的随机数质量的保证。过去,某些 rand() 的实现在随机性、分布和产生的数列周期中有严重缺陷 (在一个广为人知的例子中,最低位在调用间简单地于 1 和 0 间改变)。不推荐将 rand() 用于严肃的随机数生成需求,如加密。

POSIX requires that the period of the pseudo-random number generator used by rand is at least 2322^{32}232.
POSIX 要求 rand 所用的伪随机数生成器的周期至少为 2322^{32}232。

POSIX offered a thread-safe version of rand called rand_r, which is obsolete in favor of the drand48 family of functions.
POSIX 提供 rand 的线程安全版本,名为 rand_r,它由于 drand48 函数族而过时。

7. Exceptions (C++)

No-throw guarantee: this function never throws exceptions (该函数从不抛出异常。).

8. std::rand

Defined in header <cstdlib>

Returns a pseudo-random integral value between ​0​ and RAND_MAX (0 and RAND_MAX included).
返回 ​0​ 与 RAND_MAX (包含 0RAND_MAX) 的随机数。

std::srand() seeds the pseudo-random number generator used by rand(). If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1).
std::srand() 播种 rand() 所用的伪随机数生成器。若在任何到 srand() 的调用前使用 rand(),则 rand() 表现如同它以 srand(1) 播种。

Each time rand() is seeded with srand(), it must produce the same sequence of values on successive calls.
每次以 srand() 播种 rand() ,它必须在后续调用上产生相同的值数列。

Other functions in the standard library may call rand. It is implementation-defined which functions do so.
标准库中的其他函数可调用 rand

It is implementation-defined whether rand() is thread-safe.
rand() 是否线程安全是实现定义的。

rand() is not recommended for serious random-number generation needs. It is recommended to use C++11’s random number generation facilities to replace rand(). (since C++11)
对于严肃的随机数生成需求不推荐 rand()。推荐用 C++11 的随机数生成函数替换 rand()。(C++11 起)

//============================================================================
// Name        : Yongqiang Cheng
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif#include <cstdlib>
#include <iostream>
#include <ctime>int main()
{// use current time as seed for random generator// 以当前时间为随机生成器的种子std::srand(std::time(nullptr));int random_variable = std::rand();std::cout << "Random value on [0 " << RAND_MAX << "]: " << random_variable << '\n';return(0);
}
Random value on [0 32767]: 2085
请按任意键继续. . .

References

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

C / C++ function - rand相关推荐

  1. 彻底解决swf浏览器的缓存问题

    使用以下的方法,使SWF文件强制不从浏览器读本地的缓存.或强制其SWF文件每次都去服务器端读取最新的媒体文件,确保每次都读取最新的SWF文件. 1:使用"Expires"标头 这是 ...

  2. shell 生成指定范围随机数与随机字符串 .

    shell 生成指定范围随机数与随机字符串         分类:             shell              2014-04-22 22:17     20902人阅读     评 ...

  3. 从JavaScript数组中获取随机项[重复]

    本文翻译自:Get random item from JavaScript array [duplicate] This question already has answers here : 这个问 ...

  4. 在JavaScript中生成随机字符串/字符

    我想要一个由从[a-zA-Z0-9]随机挑选的字符组成的5个字符串. 用JavaScript做到这一点的最佳方法是什么? #1楼 我认为这将为您工作: function makeid(length) ...

  5. 红色小方块单击爆炸式展开的菜单代码

    代码简介:不知道能给它起个什么名字,就叫做"爆炸式菜单"吧,因为它的效果很像是爆炸开了,鼠标点击后会以一个五角星为基准单元依次展开,可以有多次,像链式表一样. 代码内容: < ...

  6. 关于随机验证码的一些小见解。

    随机验证码的主旨是在某一个范围内进行随机输出,在限定条件为0-9,a-z,A-Z的前提下,利用数组将这些数据都进行归纳,然后利用Math.random();返回一个新的数组,当点击button的时候, ...

  7. html贪吃蛇自动走,分享一个用html5实现的贪吃蛇特效代码

    本篇小编为大家分享一个用html5实现的简单贪吃蛇特效代码,喜欢的小伙伴们可以看一下 Snake //内置大量BUG,I'm sorry. var lev=100; //定时器间隔时间 var num ...

  8. 140个Google面试问题

    某猎头收集了140多个Google的面试题,都张到他的Blog中了,主要是下面这些职位的,因为被墙,且无任何敏感信息,所以,我原文搬过来了. Product Marketing Manager Pro ...

  9. Lua 5.1 参考手册

    Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes 云风 译 www.codingno ...

  10. mysql和hive的sql语句,hive中使用sql语句需要注意的事项

    最近在熟悉hive,使用hive中的sql语句过程中出现了一些问题. 1,hive中的insert into语句 hive> select * from t_hive2; OK 1623 611 ...

最新文章

  1. box-cox数据规整转换
  2. php程序中用户名含特殊字符怎么办,php中包含ñ等特殊字符
  3. android圆角按钮的实现
  4. HDU2553 N皇后 回溯法+打表
  5. mfc如何将一个数组中的字节数据用串口发送出去_RS232串口多机通信
  6. 如何利用wireshark对TCP消息进行分析
  7. glibc升级_Linux关于glibc等基本知识整理
  8. 软件开发过程中的Visio使用
  9. 计算机如何取消自动关机,怎么解除电脑自动关机
  10. 高强度加密vep文件提取MP4方法
  11. Handler机制整理
  12. Qt QML应用框架
  13. android支持wifi11ad,不得不知道的WIFI标准:802.11ad、ah、af
  14. 一分钟入门typescript
  15. gwas snp 和_GWAS笔记SNP过滤
  16. Policy Gradient连续动作 tf.distributions.Normal log_prob = self.normal_dist.log_prob(self.a) 的解释
  17. chrome谷歌浏览器调试微信H5页面
  18. 氢os android系统耗电,安卓用久了会卡是定制系统惹的祸?氢OS:这锅我不背!
  19. 谷歌cloud_Google Cloud如何为您的应用程序安全提供帮助?
  20. 实现微信生活缴费功能详细讲解

热门文章

  1. switch可以用什么手柄_steam设置switch手柄的步骤_Steam平台可以用switch良值pro手柄吗_怎么设置_9号资讯...
  2. 全局最小割集Stoer-Wagner算法
  3. 后缀–ize_常见词性后缀
  4. 安装Linux系统不分区的问题,浅谈linux系统的分区问题
  5. 海康摄像头录制功能实现
  6. Google Chrome浏览器常用快捷键
  7. KETTLE的文本文件输出
  8. Excel 查找函数
  9. LaTEX 表格内容换行
  10. SmartGit一个月试用期过期的解决方法