mirror of
https://github.com/hairrrrr/C-CrashCourse.git
synced 2026-02-13 15:35:38 +08:00
4-4
This commit is contained in:
37
code/practise/08 数组/02 发牌/main.c
Normal file
37
code/practise/08 数组/02 发牌/main.c
Normal file
@@ -0,0 +1,37 @@
|
||||
#include<stdio.h>
|
||||
#include<time.h>
|
||||
#include<stdbool.h>
|
||||
#include<stdlib.h>
|
||||
|
||||
#define NUM_SUIT 4
|
||||
#define NUM_RANK 13
|
||||
|
||||
int main(void) {
|
||||
|
||||
int suit, rank, num_cards;
|
||||
|
||||
const char suit_code[] = {'H', 'D', 'C', 'S'}; // heartºìÌÒ diamand·½Æ¬ club÷»¨ spadeºÚÌÒ
|
||||
const char rank_code[] = { '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' };
|
||||
bool in_hand[NUM_SUIT][NUM_RANK] = { false };
|
||||
|
||||
srand((unsigned)time(NULL));
|
||||
|
||||
printf("Enter number of cards in hand: ");
|
||||
scanf("%d", &num_cards);
|
||||
|
||||
|
||||
printf("Your card(s): ");
|
||||
while (num_cards > 0) {
|
||||
suit = rand() % NUM_SUIT;
|
||||
rank = rand() % NUM_RANK;
|
||||
|
||||
if (!in_hand[suit][rank]) {
|
||||
in_hand[suit][rank] = true;
|
||||
num_cards--;
|
||||
printf("%c%c ", suit_code[suit], rank_code[rank]);
|
||||
}
|
||||
}
|
||||
printf("\n");
|
||||
|
||||
return 0;
|
||||
}
|
||||
32
code/practise/08 数组/02 发牌/readme.md
Normal file
32
code/practise/08 数组/02 发牌/readme.md
Normal file
@@ -0,0 +1,32 @@
|
||||
#### 程序:发牌
|
||||
|
||||
下面这个程序说明了二维数组和常量数组的用法。
|
||||
|
||||
**要求:**
|
||||
|
||||
程序负责发一副标准纸牌。每张标准指派都有一个花色(梅花,方块,红桃,黑桃)和一个点数(2 ~ 10, J, Q, K, A)。用户需要指明发多少张牌:
|
||||
|
||||
```c
|
||||
Enter number of cards in hand: 5
|
||||
Your card(s): S8 SA D7 H8 SK
|
||||
```
|
||||
|
||||
**程序说明: **
|
||||
|
||||
- 创建两个常量数组,分别放置 4 中花色 和 13 个点数
|
||||
|
||||
- 程序要可以生成 随机数 。我们需要三个函数:
|
||||
|
||||
time <time.h>
|
||||
|
||||
srand <stdlib.h>
|
||||
|
||||
rand <stdlib.h>
|
||||
|
||||
这三个函数组合就可以完成这一功能,原理在我另一篇文章:【随机数发生器】 中讲解过。
|
||||
|
||||
- 生成的随机数必须在:0 ~ 3 和 0 ~ 13 之间:
|
||||
|
||||
只需要让 `rand() % 4` 那么随机数就在 0 ~ 3 之间,另一个同理。
|
||||
|
||||
- 两次拿到的牌不能是一样的。创建一个 bool 类型的数组,开始时全部初始化 false。每次拿到两个随机数后,如果数组对应的值为 false 那么将该元素置为 true 然后将此牌“发”给用户;否则,重新生成随机数。
|
||||
Reference in New Issue
Block a user