由于最近各种做实验以及期末考试,一直没有更新博客。 今天找个时间总结一下。
最近在很多实验中都需要随机数,但是使用不熟练,浪费时间去debug。
主要就是rand与srand的区别与联系
根据>http://www.cplusplus.com/reference/cstdlib/rand/ 上对rand和srand的描述以及实际实验中产生的结果,理解如下:
int rand()是产生在一定范围内(0-- RAND_MAX(32767))的一个随机整数,产生这个随机数需要一个seed(种子)(注意相同的种子会导致在调用rand()后产生相同的结果),而这个种子则是由函数void srand(unsigned a)得出。而参数a可以是任意无符号数,例如 srand(1),也可以是系统当前的时间,如 srand( (unsigned)time( NULL ) )或者srand( (unsigned)time( &t ) ),t是 time_t 类型, time_t 被定义为长整型,它返回从1970年1月1日零时零分零秒到目前为止所经过的时间,单位为秒。(注意相同的a会产生相同的种子)。
由此可知,rand与srand是配合使用的。若调用rand()之前没有调用srand(), 则系统自动调用 srand(), 且将其参数a 设置为1,即 srand(1).下面程序可以很清晰的看出这一点。
#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int main ()
{
printf ("First number: %d\n", rand()%100);// 之前没有调用srand(),则系统自动调用srand(1);
srand (time(NULL));
printf ("Random number: %d\n", rand()%100);
srand (1);
printf ("Again the first number: %d\n", rand()%100);
return 0;
}
程序结果
First number: 41 Random number: 13 Again the first number: 41
头文件:
#include<stdlib.h> //srand(), rand(), RAND_MAX(32767);
#include<time.h> //time(), time_t ;
好了,梳理好上面的关系就可以看具体应用了。
//特别注意下面公式中的 % 与 /..
1.随机生成a--b 之间的整数
srand((unsigned)time(NULL));
int t=rand()%(b-a)+a; //注意 包括a而不包括b
( 若a为0,则写作 int t=rand()%b;)
例:
随机产生1--9之间的整数
srand((unsigned)time(NULL));
int t=rand()%8+1;
2.随机生成(0,1)之间的小数
srand((unsigned)time(NULL));
float t=(float)rand()/RAND_MAX; //产生的小数包含0不包含1
还有一点需要注意:
#include<stdio.h>
#include<stdlib.h>
#define N 10
int main()
{
for(int i=0;i<100; ++i)
{
srand((unsigned)time(null));
printf("%d ", rand()%N);
}
return 0;
}
运行结果 是生成了100个相同的数。究其原因,因为函数 srand((unsigned)time(null)) 每次的初始值为系统当前的时间,因为程序执行的非常快,srand每次得到的系统时间之间相差特别小以至于 程序中srand()函数的初始值都相同,所以产生相同的种子数,因此rand()函数产生相同的随机数。
解决方法: 将 srand((unsigned)time(null)); 移到循环体外边,rand()再次调用时用到的种子是上一次rand() 函数产生的随机数(均不相同), 因此,可以得到100个随机数。