您的位置:首页 > 编程语言 > C语言/C++

c语言随机数

2016-04-18 11:43 411 查看
一、产生一个C语言随机数需要用到以下函数

#include <stdlib.h>

int rand(void); //返回一个随机数,范围在0~RAND_MAX之间

void srand(unsigned int seed); //用来设置rand()产生随机数时的随机数种子


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

用法:

生成[x,y]的伪随机数

k=x+rand()%(y-x+1)/*k即为所求范围内随机生成的数,rand()%a的结果最大为a-1*/

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):


#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
int i = 0;
int number = 0;

for (i = 0; i < 9; i++)
{
number = 1 + (int)(10.0 * rand() / (RAND_MAX + 1.0));   //产生1-10的随机数

printf("%d ", number);
}
printf("\n");

return 0;
}



可以看出每次产生的随机数都一样:


[root@localhost 2nd]# ./rand
9 4 8 8 10 2 4 8 3
[root@localhost 2nd]# ./rand
9 4 8 8 10 2 4 8 3
[root@localhost 2nd]# ./rand
9 4 8 8 10 2 4 8 3
[root@localhost 2nd]#


下面srand()用来设置rand()产生随机数时的随机数种子,使用srand((unsigned)time(NULL))系统定时/计数器的值作为随机种子


#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
int i = 0;
int number = 0;

srand((unsigned)(time(NULL))); //使用srand((unsigned)time(NULL))系统定时的值作为随机种子

for (i = 0; i < 9; i++)
{
number = 1 + (int)(10.0 * rand() / (RAND_MAX + 1.0));   //产生1-10的随机数

printf("%d ", number);
}
printf("\n");

return 0;
}


可以看出每次的结果都不一样:


[root@localhost 2nd]# ./rand
9 5 7 10 8 5 3 3 3
[root@localhost 2nd]# ./rand
3 5 5 8 7 2 7 1 1
[root@localhost 2nd]# ./rand
5 8 1 10 6 1 4 2 2
[root@localhost 2nd]# ./rand
2 6 7 6 9 1 6 8 8
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: