关于srand()函数的思考

在程序书上见到如下的一个例子,代码如下:

 1 /*****************************************
  2  * Name: deal.c
  3  * Purpose: rand
  4  * Author: zimo
  5  * Date: 02/03/2010
  6  * **************************************/

  7
  8 #include<stdio.h>
  9 #include<stdlib.h>
 10 #include<time.h>
 11
 12 #define NUM_SUITS 4
 13 #define NUM_RANKS 13
 14 #define TRUE 1
 15 #define FALSE 0
 16
 17 typedef int Bool;
 18
 19 int main(void)
 20 {
 21         Bool in_hand[NUM_SUITS][NUM_RANKS] = {0};
 22         int num_cards, rank, suit;
 23         const char rank_code[] = {'2','3','4','5','6','7','8','9','t','j','q','k','a'};
 24         const char suit_code[] = {'c','d','h','s'};
 25
 26         srand((unsigned) time(NULL));//设定随机数的产生环境,使用time函数避免产生相同的随即数
 27
 28         printf("Enter number of cards in hand:");
 29         scanf("%d", &num_cards);
 30
 31         printf("Your hand:");
 32         while(num_cards > 0)
 33         {
 34                 suit = rand() % NUM_SUITS;
 35                 rank = rand() % NUM_RANKS;
 36                 if(! in_hand[suit][rank])
 37                 {
 38                         in_hand[suit][rank] = TRUE;
 39                         num_cards--;
 40                         printf(" %c%c", rank_code[rank], suit_code[suit]);
 41                 }
 42         }
 43         printf("/n");
 44
 45         return 0;
 46 }

这段代码实现的是随即发牌程序,通篇比较容易理解,但是在srnad()这里我无法理解,这个函数到底是干嘛用的?

在标准C语言中是这样描述的:      

启动伪随机数产生器
 srand                                <stdlib.h>
       void srand(unsigned int seed);
       使用seed来初始化由rand函数调用而产生的伪随机数
相关函数   rand函数

 产生伪随机数
 rand                                   <stdlib.h>
      int rand(void);
      0到RAND_MAX(包括RAND_MAX在内)之间的伪随机整数。
  返回
相关函数  srand函数

经过思考与查阅相关资料我是这样理解的:srand()函数可以是 statr  rand,即给出初始的启动环境,rand函数是产生随机数

rand()会返回一随机数值,范围在0至RAND_MAX 间。在调用此函数产生随机数前,

先利用srand()设好随机数种子(随机数产生的初始环境),如果这个种子(初始的环境是固定地,那么产生的随机数都是一样的)

,如果未设随机数种子,rand()在调用时会自动设随机数种子为1。

同时srand和rand是一组函数,使用时应该一起使用。

例如当srand(n)时,初始的环境是n,接下来 j=(int)n*rand()/(RAND_MAX+1.0)表明随机数j是在0--n之间产生

这些是我个人的理解,我觉得比我理解好的是这个链接:http://blog.csdn.net/zqy2000zqy/archive/2006/09/04/1174978.aspx

都可以看看。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值