/*********************************************************
* From C PROGRAMMING: A MODERN APPROACH, by K. N. King *
* Copyright (c) 1996 W. W. Norton & Company, Inc. *
* All rights reserved. *
* This program may be freely distributed for class use, *
* provided that this copyright notice is retained. *
*********************************************************/
/* deal.c (Chapter 8, page 150) */
/* Deals a random hand of cards */
/*發牌*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NUM_SUITS 4 //4個花色
#define NUM_RANKS 13 //每個花色13張牌
#define TRUE 1
#define FALSE 0
typedef int Bool; //定義新資料類型Bool
main()
{
Bool in_hand[NUM_SUITS][NUM_RANKS] = {0}; //定義二維數組in_hand 4行13列
int num_cards, rank, suit;
const char rank_code[] = {'2','3','4','5','6','7','8',
'9','t','j','q','k','a'}; //數組中存13牌
const char suit_code[] = {'c','d','h','s'}; //數組中存4個花色
// c,d,h,s代表梅花、紅桃 、方片 、黑桃四種花色
//聲明為const的數組不能進行修改
srand((unsigned) time(NULL));
//srand函數:初始化C語言的随機數生成器,通過把time函數的傳回值傳遞給srand這種方法
//可以避免程式在每次運作時發同樣的牌
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");
return 0;
}
本文轉自dllglvzhenfeng51CTO部落格,原文連結:http://blog.51cto.com/1443208/313597,如需轉載請自行聯系原作者