本文实例为大家分享了C语言实现随机抽取纸牌的具体代码,供大家参考,具体内容如下
程序设计要求
本程序负责发一副标准纸牌,每张标准纸牌都有一种花色(梅花、方块、黑桃、红桃)和一个等级(2,3,4,5,6…K,A)。程序需要用户指明手机有几张牌。
程序设计流程
1 . 使用库函数和时间函数,用time函数返回当前时间,用一个数表示,srand函数初始化C语言的随机数生成器。通过把time函数返回值传递给srand可以避免程序每次运行发同样的牌。rand函数产生随机数,通过%缩放。
2 . 使用二位数组来进行数据记录。4行表示每种花色,13列表示每种等级。
3 . 程序开始时,数组元素都为false,每随机抽取一张纸牌时,检查in_hand对应元素真假,如果为真,则抽取其他纸牌,如果为假,记录到数组元素当中,提醒我们这张牌已经记录过了。
效果展示
完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
#include <stdio.h> #include <ctype.h> #include <stdbool.h> #include <time.h> #include <stdlib.h> # define num_rates ((int) (sizeof(value)/sizeof(value[0]))) # define initial_balance 100.00 #define num_suits 4 #define num_ranks 13 int main(){ bool in_hand[num_suits][num_ranks] = { false }; int num_cards,rank,suit; const char rank_code[] = { '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 't' , 'j' , 'q' , 'k' , 'a' }; const char suit_code[] = { 'c' , 'd' , 'h' , 's' }; printf ( "enter number\n" ); scanf ( "%d" ,&num_cards); printf ( "your hands\n" ); while (num_cards>0){ suit = rand ()%num_suits; rank = rand ()%num_ranks; 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; } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/weixin_45743799/article/details/104536686