srand()和rand()函数的使用

rand()函数不接受参数,默认以1为种子(即起始值)。 随机数生成器总是以相同的种子开始,所以形成的伪随机数列也相同,失去了随机意义。(但这样便于程序调试) 

srand()函数就是指明种子的大小;只要种子不同,那么每次随机到的值或者固定范围的序列就不一样,达到完全随机。

代码1.给固定的种子,每次得到固定的随机值:

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 int func1(int *a)
 4 {
 5   return (*a%65)+(int)(rand()/(RAND_MAX+1.0));
 6 
 7 }
 8 
 9 int func2(int *a,char *b)
10 {
11   int tmp1;
12   tmp1 = atoi(b);
13   return (*a%tmp1)+(int)(rand()/RAND_MAX+1);
14 }
15 
16 int main(int argc,char **argv)
17 {
18 if(argc==2)
19 {
20   int tmp = atoi(argv[1]);
21   srand((unsigned int)tmp);
22   printf("%d
",func1(&tmp));
23 
24 }
25 if(argc == 3)
26 {
27   int tmp=atoi(argv[1]);
28   srand((unsigned int)tmp);
29   printf("%d
",func2(&tmp,argv[2]));
30 }
31 }

代码2,达到完全的随机

 1 #include<time.h>
 2 
 3 #include<stdlib.h>
 4 
 5 #include<stdio.h>
 6 
 7 void main()
 8 
 9 {
10 
11 int i,j;
12 
13 srand((int)time(0));
14 
15 for(i=0;i<10;i++)
16 
17 {
18 
19 j=1+(int)(10.0*rand()/(RAND_MAX+1.0));
20 
21 printf("%d",j);
22 
23 }
24 
25 }
原文地址:https://www.cnblogs.com/defen/p/5528669.html