Chinaunix首页 | 论坛 | 博客
  • 博客访问: 173964
  • 博文数量: 31
  • 博客积分: 1075
  • 博客等级: 少尉
  • 技术积分: 215
  • 用 户 组: 普通用户
  • 注册时间: 2008-04-01 17:51
个人简介

1

文章分类

全部博文(31)

文章存档

2013年(1)

2012年(4)

2010年(26)

我的朋友

分类: LINUX

2010-07-28 20:29:29

首先把网上的资料现整理了,然后在贴几个自己写的随机函数

1.rand()与srand()


在C语言函数库中包含了一个产生随机数的函数:
int rand( void );
在函数库中对这个函数的说明是:

The rand function returns a pseudorandom integer in the range

0 to RAND_MAX. Use the srand function to seed the pseudorandom

-number generator before calling rand.

而在C语言函数库中是这样定义RAND_MAX的:

/* Maximum value returned by "rand" function
*/
#define RAND_MAX 0x7FFF

所以,函数int rand( void );返回的是一个界于0~32767(0x7FFF)之

间的伪随机数,包括0和32767。注意,这里产生的是伪随机数,不是真正意

义上的随机数,看下面的程序:

#include "stdlib.h"
#include "stdio.h"

void main( void )
{
/* Display a number. */
printf( " %6d\n", rand() );

getchar();
}
程序运行的结果是:
346

多次运行这个程序,发现每次产生的结果都是346(不同的机器可能产生

的结果不一样),这就是所谓的伪随机数。伪随机数是通过一个公式来运算

出来的,所以,每次产生的伪随机数都一样。那么,如何才能产生真正意义

上的随机数呢?这就有一个随机种子的问题。在C语言标准函数库中,有这

么一个函数:

void srand( unsigned int seed );

在《The c programming language》中对这个函数是这样描述的:
srand uses seed(函数变量声明中的seed) as the seed(随机函数中种子

的意思) for a new sequence of pseudo-random numbers. The

initial seed is 1.

所以,要产生真正意义上的随机数,那么就要求每次提供的种子不一样,一

般情况下,都设置时间为随机函数的种子。看下面的一段程序:

/* RAND.C: This program seeds the random-number generator
* with the time, then displays 10 random integers.
*/

#include "stdlib.h"
#include "stdio.h"
#include "time.h"

void 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() );
}
Output

6929
8026
21987
30734
20587
6699
22034
25051
7988
10104

每次运行这个程序,产生的随机数都不一样,这样就达到了随机数的要求了

2.random与randomize()

打开标准库中的头文件 Stdlib.h 就会发现有这样的一条语句:
#define random(num) (rand() % (num))

可见要产生给定范围的随机数,可以使用random()。

#define randomize() srand((unsigned)time(NULL))

srand( (unsigned)time( NULL ) );
/* Display 10 numbers. */
for( i = 0; i < 10;i++ )
printf( “ %6d\n”, rand() );
}

randomize();
/* Display 10 numbers. */
for( i = 0; i < 10;i++ )
printf( “ %6d\n”, rand() );
}

2者等价

阅读(2171) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~