设为首页 加入收藏

TOP

C语言产生伪随机数
2014-11-23 23:24:19 来源: 作者: 【 】 浏览:1
Tags:语言 产生 随机

MSDN中的例子。
// crt_rand.c
// This program seeds the random-number generator
// with the time, then displays 10 random integers.
//
#include
#include
#include
int main( void )
{
int i;

// Seed the random-number generator with current time so that
// the numbers will be different every time we run.
//
srand( (unsigned)time( NULL ) );
// Display 10 numbers.
for( i = 0; i < 10;i++ )
printf( " %6d\n", rand() );
printf("\n");
// Usually, you will want to generate a number in a specific range,
// such as 0 to 100, like this:
{
int RANGE_MIN = 0;
int RANGE_MAX = 100;
for (i = 0; i < 10; i++ )
{
int rand100 = (((double) rand() /
(double) RAND_MAX) * RANGE_MAX + RANGE_MIN);
printf( " %6d\n", rand100);
}
}

我们知道rand()函数可以用来产生随机数,但是这不是真真意义上的随机数,是一个伪随机数,是根据一个数,我们可以称它为种了,为基准以某个递推公式推算出来的一系数,当这系列数很大的时候,就符合正态公布,从而相当于产生了随机数,但这不是真正的随机数,当计算机正常开机后,这个种子的值是定了的,除非你破坏了系统,为了改变这个种子的值,
rand() 返回0至RAND_MAX之间的随机整数值
srand()用来设置rand()产生随机数时的随机数种子。参数seed必须是个整数,通常可以利用geypid()或time(0)的返回值来当做seed。如果每次seed都设相同值,rand()所产生的随机数值每次就会一样。即如果去掉 srand( (unsigned)time( NULL ) );则每次运行产生的随机数相同。

作者“菜鸟变身记”

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇看图理解单链表的反转 下一篇通过余弦定理从点积的定义推出点..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: