现在的位置: 首页 > 综合 > 正文

产生不重复的随机牌

2013年03月13日 ⁄ 综合 ⁄ 共 807字 ⁄ 字号 评论关闭

《C语言程序设计:现代方法》p121例

/*************************************************
 *
 *本程序根据用户的输入,生成相应数量的扑克牌。
 *
 * ************************************************/
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <stdbool.h>

#define NUM_SUITS 4
#define NUM_RANKS 13

int main(void){

    int num_cards, suit, rank;
    //用于记录牌的数字及花色。
    const char suit_code[4]={'a','b','c','d'};
    const char rank_code[13]={'1','2','3','4','5','6','7','8','9', 't', 'J','Q','K'};
    //用于记录某个牌是否已经发出去。
    bool isCardExist[NUM_RANKS][NUM_SUITS]={false};

    printf("How many cards do you want: ");
    scanf("%d", &num_cards);

    printf("Your cards are: ");
    srand((unsigned long)time(NULL));
    for(int i=0; i<num_cards; i++){
        suit=rand()%NUM_SUITS;
        rank=rand()%NUM_RANKS;
        if(isCardExist[rank][suit]==false){
            isCardExist[rank][suit]=true;
            printf("%c%c  ", rank_code[rank], suit_code[suit]);
        }
        else
            i--;
    }
    printf("\n");
    
    return 0;
}

抱歉!评论已关闭.