C语言随机数的实现

来源:互联网 发布:范德堡大学知乎 编辑:程序博客网 时间:2024/05/01 23:25

C语言随机数的实现

此次笔记基于《C语言程序设计--现代方法》。通过一个发牌的程序说明。

此程序负责发一副纸牌。每张纸牌有一个花色(suit)和一个等级(rank)。程序需要用户输入手里应握有几张纸牌。


为了随机抽取纸牌,采用一些C语言的库函数。time函数返回当前的时间,用一个数表示。srand函数初始化C语言的随机数生成器通过把time函数的返回值传递给函数srand可以避免程序在每次运行时发同样的牌。rand函数在每次调用时会产生一个看似随机的数。通过采用%用算符,可以缩放rand函数的返回值,使其落在0~3(表示花色)或者是0~12(表示等级)的范围内。

程序如下:

/********************************************** * deal.c                                     * * Deals a random hand of cards               * **********************************************/#include<stdio.h>#include<stdlib.h>#include<stdbool.h>         /*C99 only*/#include<time.h>#define NUM_SUITS 4#define NUM_RANKS 13int main(void){    bool in_hand[NUM_SUITS][NUM_RANKS] = {false};    int num_cards, rank, suit;    const char rank_code[] = {'2','3','4','5','6','7','8',                              '9','t','j','q','k','a'};    const char suit_code[] = {'c','d','h','s'};    srand((unsigned) time(NULL));    printf("Enter number of cards in hand: ");    scanf("%d",&num_cards);    printf("Your hand:");    while (num_cards > 0)    {        suit = rand() % NUM_SUITS;  /*picks a random suit*/        rank = rand() % NUM_RANKS;  /*picks a random rank*/        if (!in_hand[suit][rank])        {            in_hand[suit][rank] = true;            num_cards--;            printf(" %c%c", rank_code[rank], suit_code[suit]);        }    }    printf("\n");    system("pause");    return 0;}


原创粉丝点击