Date:1.2
在rand()之前使用srand()?
使用:每次产生随机数不同
不使用:每次产生的随机数相同
- #include "stdafx.h"
- #include <time.h>
- #include <stdlib.h>
- #define SUITS 4
- #define FACES 13
- #define CARDS 52
- void shuffle(unsigned int wDeck[][FACES]) //洗牌 deck表示一副牌
- {
- for (size_t card = 1; card <= CARDS; card++)
- {
- size_t row;
- size_t column;
- do {
- row = rand() % SUITS;
- column = rand() % FACES;
- } while (wDeck[row][column] != 0);
- wDeck[row][column] = card;
- }
- }
- void deal(unsigned int wDeck[][FACES], const char *wFace[], const char *wSuit[])
- {
- for (size_t card = 1; card < CARDS; card++)
- {
- for (size_t row = 0; row < SUITS; row++)
- {
- for (size_t column = 0; column < FACES; column++)
- {
- if (wDeck[row][column] == card) {
- printf("%5s of %-8s%c", wFace[column], wSuit[row], card % 2 == 0 ? ‘\\n‘ : ‘\\t‘);
- }
- }
- }
- }
- }
- int main()
- {
- unsigned int deck[SUITS][FACES];
- memset(deck, 0, sizeof(deck));
- srand(time(NULL));
- shuffle(deck); //洗牌
- const char *suit[SUITS] = { "红桃","方块","梅花","黑桃" };
- const char *face[FACES] = { "Ace","Deuce","Three" ,"Four" ,"Five" ,"Six" ,"Seven" ,"Eight",
- "Nine","Ten","Jack","Queen","King" };
- deal(deck, face, suit); //发牌
- getchar();
- return 0;
- }
算法有缺陷( deal()函数 如果已有 wDeck[row][column] == card 循环还是会继续 ),之后改进。