# C Primer Plus 第12章 12.4 随机数函数和静态变量

2016/11/24 05:59

``````/* rand0.c --产生随机数    */
/* ANSI C 的可移植算法     */
static unsigned long int next = 1;  /*种子*/
int rand0(void)
{
/*产生伪随机数的魔术般的公式    */
next = next * 1103515245 + 12345;
return (unsigned int)(next/65536) % 32768;
}``````

``````/*r_drive0.c --测试rand0()函数*/
/*与rand0.c一起编译*/
#include <stdio.h>
extern int rand0(void);

int main(void)
{
int count;

for(count=0;count<5;count++)
printf("%hd\n",rand0());

return 0;
}``````

``````16838
5758
10113
17515
31051
``````

``````16838
5758
10113
17515
31051``````

``````/*s_and_r.c  --包含函数rand1()和srand1()的文件*/
/*使用ANSI C 的可移植算法*/
static unsigned long int next = 1;  /*种子*/
int rand1(void)
{
/*产生随机数的魔术般的公式*/
next = next*1103515245 + 12345;
return (unsigned int)(next/65536)%32768;
}

void srand1(unsigned int seed)
{
next = seed;
}``````

``````/* r_drive1.c  测试函数rand1()和srand1()  */
/*与s_and_r.c 一起编译*/
#include <stdio.h>
extern void srand1(unsigned int x);
extern int rand1(void);

int main(void)
{
int count;
unsigned seed;

while(scanf("%u",&seed)==1)
{
srand1(seed);  /*重置种子*/
for(count=0;count<5;count++)
printf("%hd\n",rand1());
printf("Please enter next seed(q to quit): \n");
}
printf("Done\n");
return 0;
}``````

``````please enter your choice for seed.
1
16838
5758
10113
17515
31051
3
20067
23475
8955
20841
15324
q
Done``````

``````#include <time.h>                     /*为time()函数提供ANSI原型*/
srand1((unsigned int) time(0))    /*初始化种子*/``````

0
0 收藏

0 评论
0 收藏
0