c语言随机数

一、产生一个C语言随机数需要用到以下函数

1 #include <stdlib.h>
2 
3 int rand(void); //返回一个随机数,范围在0~RAND_MAX之间
4 
5 void srand(unsigned int seed); //用来设置rand()产生随机数时的随机数种子

rand函数返回一个随机数,范围在0~到RAND_MAX之间

用法:

1 生成[x,y]的伪随机数
2 
3 k=x+rand()%(y-x+1)/*k即为所求范围内随机生成的数,rand()%a的结果最大为a-1*/
4 
5 j=(int)(n*rand()/(RAND_MAX+1.0)) /*产生一个0到n之间的随机数*/

srand()用来设置rand()产生随机数时的随机数种子。参数seed必须是个整数,一般使用srand((unsigned)time(NULL))系统定时/计数器的值作为随机种子。

每个种子对应一组根据算法预先生成的随机数,所以,在相同的平台环境下,不同时间产生的随机数会是不同的如果每次seed都设相同值,rand()所产生的随机数值每次就会一样。

rand()函数默认情况下初始化种子值为1;

 

下面我们产生介于1 到10 间的随机数值,暂时没有设置srand随机数种子(rand()函数默认情况下初始化种子值为1):
 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <time.h>  
 4  
 5 int main()
 6 {
 7     int i = 0;
 8     int number = 0;
 9  
10     for (i = 0; i < 9; i++)
11     {   
12         number = 1 + (int)(10.0 * rand() / (RAND_MAX + 1.0));   //产生1-10的随机数
13 
14         printf("%d ", number);
15     }   
16     printf("
");
17     
18     return 0;
19 }

可以看出每次产生的随机数都一样:
1 [root@localhost 2nd]# ./rand
2 9 4 8 8 10 2 4 8 3 
3 [root@localhost 2nd]# ./rand
4 9 4 8 8 10 2 4 8 3 
5 [root@localhost 2nd]# ./rand
6 9 4 8 8 10 2 4 8 3 
7 [root@localhost 2nd]# 
下面srand()用来设置rand()产生随机数时的随机数种子,使用srand((unsigned)time(NULL))系统定时/计数器的值作为随机种子
 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <time.h>  
 4  
 5 int main()
 6 {
 7     int i = 0;
 8     int number = 0;
 9 
10     srand((unsigned)(time(NULL))); //使用srand((unsigned)time(NULL))系统定时的值作为随机种子
11  
12     for (i = 0; i < 9; i++)
13     {   
14         number = 1 + (int)(10.0 * rand() / (RAND_MAX + 1.0));   //产生1-10的随机数
15 
16         printf("%d ", number);
17     }   
18     printf("
");
19     
20     return 0;
21 }
可以看出每次的结果都不一样:
1 [root@localhost 2nd]# ./rand     
2 9 5 7 10 8 5 3 3 3 
3 [root@localhost 2nd]# ./rand
4 3 5 5 8 7 2 7 1 1 
5 [root@localhost 2nd]# ./rand
6 5 8 1 10 6 1 4 2 2 
7 [root@localhost 2nd]# ./rand
8 2 6 7 6 9 1 6 8 8 
原文地址:https://www.cnblogs.com/wenqiang/p/5403727.html