产生不重复的随机牌 2013-02-04 22:06 413人阅读 评论(0) 收藏
《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;
}版权声明:本文为博主原创文章,未经博主允许不得转载。
欢迎转载,请注明来自:
www.lujinhong.com
www.cnblogs.com/lujinhong2

浙公网安备 33010602011771号