rand()
在很多时候我们都会用到随机数,比如代码测试,想自己制造一些数据,许多人也会第一时间想到rand()这个随机生成的函数
来自官方的解释:
不喜欢看英文的小伙伴可以跳过
int rand (void);
Returns a pseudo-random integral number in the range between 0
and RAND_MAX.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.RAND_MAX is a constant defined in .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:
123
v1 = rand() % 100; // v1 in the range 0 to 99
v2 = rand() % 100 + 1; // v2 in the range 1 to 100
v3 = rand() % 30 + 1985; // v3 in the range 1985-2014
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 for more info).
传送门
言归正传,rand()是通过某种算法,产生一个随机序列然后从中选出,并生成一个伪随机数,如果只是用rand的话,你会发现无论你的程序运行多少次,你得到的随机数都是一样的

然后我们继续想,如果不赋值,直接输出rand,结果会一样吗?

结果并不是我们想象的那样,一直不变,原因就是rand生成的是伪随机数,也就是它是通过某种方式生成了一段数的序列,也就是说我们打印的相当于是已经打乱顺序,储存好在数组的元素,因为随机种子一直没变。
由于种子没变,随机序列也就没变,也就是说你用某种算法产生了一个伪随机数列,提前存储在一个数据结构里面,然后每次rand的时候就把序列中的元素拿出来一个。(可以想象成一个数组,每次调用rand,指针向后移一位)
(个人观点,欢迎斧正)
想要多次生成不同的的随机数就需要用到下面的这个函数。
srand
srand也包含在cstdlib里面,此函数是为了生成随机种子,然后让系统产生的随机数不同,通常我们可以结合time使用,time能获取系统时间,让种子不断的随着时间变化,这样就能产生不同的随机数列,也就能用rand产生不同的随机数
time的头文件为ctime
具体食用方法如下:

现在产生的随机数每次运行都不一样。
code:
#include
#include
#include
#include
//头文件觉得写着麻烦的话可以偷偷懒,写一个#include就行
using namespace std;
int main(void)
{
srand((int)time(0));//这里也可以用NULL代替time里面的0
cout
关注
打赏