【问题标题】:C - Sorting numbers with names attachedC - 对附有名称的数字进行排序
【发布时间】:2019-07-31 04:00:58
【问题描述】:

我是编程初学者,有人可以帮我解答这个问题吗? 此代码适用于公牛和奶牛游戏,我需要对所做的猜测进行名人堂。名人堂也需要之前输入的演员的名字。

for (b = 0; b < ch - 1; b++) {
    for (c = 0; c < ch - b - 1; c++) {
        if (array[c] > array[c + 1]) {
            sort = array[c];
            array[c] = array[c + 1];
            array[c + 1] = sort;
            //sorting the guessing result in ascending order
        }
    }
}
//printing to a file
printf("Sorted list in ascending order:\n");

for (b = 0; b < ch; b++)
    printf("%d\n", array[b]);

fprintf(file, "Sorting: %s %d\n", user_name, ch);
fclose(file);

【问题讨论】:

标签: c arrays function sorting


【解决方案1】:

对“带有附加名称的数字”进行排序的一种简单方法是将数字和名称放入struct 并拥有一个包含此struct 的数组。然后只需使用标准的qsort 函数对数组进行排序。

可能是这样的:

#include <stdio.h>
#include <stdlib.h>

// Define a type to hold the score together with the name of the player
typedef struct
{
    char name[42];
    int score;
} PlayerStats;

// Make a compare function to be used by qsort
int cmpfunc (const void * a, const void * b){
    const PlayerStats* pA = a;
    const PlayerStats* pB = b;
    if (pA->score > pB->score) return -1;
    if (pA->score < pB->score) return 1;
    return 0;
}

// A function for printing the players and their score
void print_stats(PlayerStats *ps, size_t n)
{
    for(size_t i=0; i<n; ++i) printf("%s : score=%d\n", ps[i].name, ps[i].score);
}

int main(){
    // Make an array of players with scores.
    PlayerStats player_stats[3] = {{"p1", 17}, {"p2", 9}, {"p3", 42}};
    size_t numElements = sizeof player_stats / sizeof player_stats[0];
    size_t sizeElement = sizeof player_stats[0];

    printf("Unsorted:\n");
    print_stats(player_stats, numElements);

    // Use the standard qsort for sorting the array
    qsort(player_stats, numElements, sizeElement, cmpfunc);

    printf("Sorted:\n");
    print_stats(player_stats, numElements);

    return 0;
}

输出:

Unsorted:
p1 : score=17
p2 : score=9
p3 : score=42
Sorted:
p3 : score=42
p1 : score=17
p2 : score=9

在这里试试:https://ideone.com/HMgDbn

如果您想要升序排序,您只需更改比较函数,如下所示:

int cmpfunc (const void * a, const void * b){
    const PlayerStats* pA = a;
    const PlayerStats* pB = b;
    if (pA->score > pB->score) return 1;   // Change -1 to 1
    if (pA->score < pB->score) return -1;  // Change 1 to -1
    return 0;
}

【讨论】:

    猜你喜欢
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多