rand函数和srand函数:产生随机数-ZT

来源:互联网 发布:淘宝卖家轰炸机 编辑:程序博客网 时间:2024/05/12 02:19

ZT:http://blog.csdn.net/ycs0501/archive/2009/03/09/3973568.aspx

 

rand(产生随机数)
相关函数
srand

表头文件
#include<stdlib.h>

定义函数
int rand(void)

函数说明
rand()会返回一随机数值,范围在0至RAND_MAX 间。在调用此函数产生随机数前,必须先利用srand()设好随机数种子,如果未设随机数种子,rand()在调用时会自动设随机数种子为1。关于随机数种子请参考srand()。

返回值
返回0至RAND_MAX之间的随机数值,RAND_MAX定义在stdlib.h,其值为2147483647。

范例
/* 产生介于1 到10 间的随机数值,此范例未设随机数种子,完整的随机数产生请参考
srand()*/
#include<stdlib.h>
main()
{
int i,j;
for(i=0;i<10;i++)
{
j=1+(int)(10.0*rand()/(RAND_MAX+1.0));
printf("%d ",j);
}
}

执行
9 4 8 8 10 2 4 8 3 6
9 4 8 8 10 2 4 8 3 6

 

 

srand(设置随机数种子)
相关函数
rand

表头文件
#include<stdlib.h>

定义函数
void srand (unsigned int seed);

函数说明
srand()用来设置rand()产生随机数时的随机数种子。参数seed必须是个整数,通常可以利用geypid()或time(0)的返回值来当做seed。如果每次seed都设相同值,rand()所产生的随机数值每次就会一样。

返回值

范例
/* 产生介于1 到10 间的随机数值,此范例与执行结果可与rand()参照*/
#include<time.h>
#include<stdlib.h>
main()
{
int i,j;
srand((int)time(0));
for(i=0;i<10;i++)
{
j=1+(int)(10.0*rand()/(RAND_MAX+1.0));
printf(" %d ",j);
}
}

执行
5 8 8 8 10 2 10 8 9 9
2 9 7 4 10 3 2 10 8 7

附:

函数名: random
功 能: 随机数发生器
用 法: int random(int num);
程序例:

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

/* prints a random number in the range 0 to 99 */
int main(void)
{
randomize();
printf("Random number in the 0-99 range: %d/n", random (100));
return 0;
}

 

函数名: randomize
功 能: 初始化随机数发生器
用 法: void randomize(void);
程序例:

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

int main(void)
{
int i;

randomize();
printf("Ten random numbers from 0 to 99/n/n");
for(i=0; i<10; i++)
printf("%d/n", rand() % 100);
return 0;
}

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/ycs0501/archive/2009/03/09/3973568.aspx

原创粉丝点击