在c ++中使用srand() [英] use of srand() in c++

查看:234
本文介绍了在c ++中使用srand()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是c ++的新手,所以这个疑问可能看起来基本,但我没有得到rand()和srand()和srand()之间的种子的意思是什么区别?
当我写srand(time(NULL)),它做什么来生成随机数,什么时间(NULL)这里做?它是什么?
提前感谢

I am new to c++ so this doubt might look basic but I am not getting the difference between rand() and srand() and what do u mean by "seed" in srand()? when I write srand(time(NULL)), what does it do to generate random numbers, what does time(NULL) do here? and what is it? Thanks in advance

推荐答案

随机数生成器需要一个数字(称为seed)来生成随机数。如果随机数生成器被给予相同的种子,则每次它将生成相同的随机数序列。例如: -

A random number generator requires a number(it is called seed) to generate random numbers . If the random number generator is given the same seed then every time it will generate the same sequence of random numbers . For example :-

如果运行程序,它正在生成随机序列2,78,45,60。
如果第二次运行程序,您将再次得到相同的序列2,78,45,60。

If you run the program and it is generating random sequence 2,78,45,60 . If second time you run the program you will again get the same sequence 2,78,45,60.

srand函数用于更改随机数生成器。通过设置srand(time(NULL)),您将随机数生成器的种子设置为当前时间。通过每次运行程序,您将获得不同的随机序列: -

srand function is used to change the seed of the random number generator.By setting srand(time(NULL)) , you are setting the seed of the random number generator to the current time.By doing this every time you run the program you will get different random sequences :-

例如对于第一次运行,如果你得到2,78,45,60。
下次你可能会得到5,3,6,80(根据当前时间,因为种子已经更改,因为时间已经改变自上次运行)

For example for the first run if you are getting 2,78,45,60 . Next time you might get 5,3,6,80 (depending on the current time,as seed has been changed since the time has changed since the last run)

有关详情,请参阅: -

for more info refer these :-

http://www.cplusplus.com/reference/clibrary/cstdlib/rand/

http://www.cplusplus.com/reference/clibrary/cstdlib/srand/

http://www.cplusplus.com/reference / clibrary / ctime / time /

这篇关于在c ++中使用srand()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆