编写c语言程序在数组pai a[52]={{1,'a'},{1,'b'}........} 中随意抽出20张牌,放在数组int b[20]={........}中,单独排序,编一个函数程序来完成这项任务。
时间: 2024-02-28 10:52:12 浏览: 28
以下是一个C语言的示例程序,可以完成你的要求:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct Card {
int number;
char suit;
};
void shuffle(struct Card* deck, int size) {
srand(time(NULL));
for (int i = 0; i < size; i++) {
int j = rand() % size;
struct Card temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
}
int cmp(const void* a, const void* b) {
struct Card* card_a = (struct Card*)a;
struct Card* card_b = (struct Card*)b;
return card_a->number - card_b->number;
}
void sort_cards(struct Card* hand, int size) {
qsort(hand, size, sizeof(struct Card), cmp);
}
int main() {
struct Card deck[52] = {
{1, 'a'}, {1, 'b'}, {1, 'c'}, {1, 'd'},
{2, 'a'}, {2, 'b'}, {2, 'c'}, {2, 'd'},
{3, 'a'}, {3, 'b'}, {3, 'c'}, {3, 'd'},
{4, 'a'}, {4, 'b'}, {4, 'c'}, {4, 'd'},
{5, 'a'}, {5, 'b'}, {5, 'c'}, {5, 'd'},
{6, 'a'}, {6, 'b'}, {6, 'c'}, {6, 'd'},
{7, 'a'}, {7, 'b'}, {7, 'c'}, {7, 'd'},
{8, 'a'}, {8, 'b'}, {8, 'c'}, {8, 'd'},
{9, 'a'}, {9, 'b'}, {9, 'c'}, {9, 'd'},
{10, 'a'}, {10, 'b'}, {10, 'c'}, {10, 'd'},
{11, 'a'}, {11, 'b'}, {11, 'c'}, {11, 'd'},
{12, 'a'}, {12, 'b'}, {12, 'c'}, {12, 'd'},
{13, 'a'}, {13, 'b'}, {13, 'c'}, {13, 'd'}
};
shuffle(deck, 52);
int b[20] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
struct Card hand[20];
for (int i = 0; i < 20; i++) {
hand[i] = deck[b[i]];
}
sort_cards(hand, 20);
for (int i = 0; i < 20; i++) {
printf("%d%c ", hand[i].number, hand[i].suit);
}
printf("\n");
return 0;
}
```
程序首先定义了一个结构体 `Card`,表示一张牌,包括一个数字和一个花色。然后定义了一个 `shuffle` 函数,用于打乱牌组。之后定义了一个 `cmp` 函数,用于排序时比较两张牌的大小。最后定义了 `sort_cards` 函数,用于对手中的牌进行排序。
在 `main` 函数中,首先调用 `shuffle` 函数打乱牌组,然后定义了一个数组 `b`,表示要抽出的牌在牌组中的索引。接着通过循环将抽出的牌存入 `hand` 数组中,最后调用 `sort_cards` 函数对 `hand` 数组进行排序。最后输出排序后的牌。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)