|
发表于 2023-12-15 01:42:57
|
显示全部楼层
可以使用结构体数组来存储棋手信息,并使用冒泡排序算法进行排序。以下是一个可能的实现:
- #include <stdio.h>
- #include <string.h>
- // 定义棋手结构体
- struct ChessPlayer {
- char id[5]; // 棋手编号
- char name[20]; // 棋手姓名
- char identity[10]; // 棋手身份
- char rank[10]; // 棋手段位
- int score; // 等级分
- };
- // 冒泡排序函数,按score升序排序
- void bubbleSortByScore(struct ChessPlayer players[], int n) {
- for (int i = 0; i < n - 1; i++) {
- for (int j = 0; j < n - 1 - i; j++) {
- if (players[j].score > players[j+1].score) {
- // 交换两个棋手的信息
- struct ChessPlayer temp = players[j];
- players[j] = players[j+1];
- players[j+1] = temp;
- }
- }
- }
- }
- // 冒泡排序函数,按rank降序排序
- void bubbleSortByRank(struct ChessPlayer players[], int n) {
- for (int i = 0; i < n - 1; i++) {
- for (int j = 0; j < n - 1 - i; j++) {
- // 先比较段位
- int cmpResult = strcmp(players[j].rank, players[j+1].rank);
- if (cmpResult < 0 || (cmpResult == 0 && strcmp(players[j].id + 1, players[j+1].id + 1) > 0)) {
- // 交换两个棋手的信息
- struct ChessPlayer temp = players[j];
- players[j] = players[j+1];
- players[j+1] = temp;
- }
- }
- }
- }
- int main() {
- struct ChessPlayer players[] = {
- { "P001", "连笑", "职业", "九段", 8900 },
- { "P002", "柯洁", "职业", "九段", 9422 },
- // 添加更多棋手信息...
- };
- int numPlayers = sizeof(players) / sizeof(struct ChessPlayer);
- while (1) {
- char choice;
- printf("请选择排序方式(A-按等级分升序排序 B-职业棋手按段位降序排序 C-退出): ");
- scanf("%c", &choice);
- getchar(); // 读取并丢弃输入缓冲区中的换行符
- // 根据用户的选择进行排序并输出结果
- switch (choice) {
- case 'A':
- bubbleSortByScore(players, numPlayers);
- break;
- case 'B':
- bubbleSortByRank(players, numPlayers);
- break;
- case 'C':
- return 0;
- default:
- printf("无效选择,请重新输入。\n");
- continue;
- }
- // 输出排序结果
- printf("排序结果:\n");
- printf("棋手编号 棋手姓名 棋手身份 棋手段位 等级分\n");
- for (int i = 0; i < numPlayers; i++) {
- printf("%s %s %s %s %d\n", players[i].id, players[i].name, players[i].identity, players[i].rank, players[i].score);
- }
- printf("\n");
- }
- return 0;
- }
复制代码
该程序先定义了一个棋手结构体,然后使用该结构体数组存储棋手信息。冒泡排序函数`bubbleSortByScore`按照等级分升序排序,而`bubbleSortByRank`按照段位降序排序。通过不断接收用户的选择,并根据选择进行对应的排序和输出。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|