简体   繁体   English

将要显示的功能输出从高到低排序

[英]Sorting the output of a function to display from High to Low

I have a struct, defined as this: 我有一个结构,定义为:

typedef struct structure
{
char names[20];
int scores[4];
float average;
char letter;
} stuff;

And from that struct created this array: 然后从该结构创建此数组:

stuff everything[13];

Later, a function called with: 后来,一个函数调用了:

display(everything);

displays to the screen a basic chart that displays 13 Names, 13 test1s, 13 test2s, 13 test3s, 13 test4s, 13 averages, and 13 letter grades, in no order. 在屏幕上显示一个基本图表,该图表按顺序显示13个名称,13个test1、13个test2、13个test3、13个test4、13个平均值和13个字母等级。 For reference, the function looks like this: 作为参考,该函数如下所示:

void display(stuff *everything)
{
int q = 0;

printf("\n\n Name \t\t E1 \t E2 \t E3 \t E4 \t Avg \t Grade");
for(q=0; q<13; q++)
{
printf("\n %s \t %d \t %d \t %d \t %d \t %.2f \t %c", 
everything[q].names,
everything[q].scores[0],
everything[q].scores[1],
everything[q].scores[2], 
everything[q].scores[3],
everything[q].average,
everything[q].letter);
}
return;
}

I would like to to take the averages and compare them against each other so that when it displays to the screen, the first result is the highest average, and it goes down from there. 我想取平均值并相互比较,以便在屏幕上显示时,第一个结果是最高平均值,并且从那里开始下降。 I'm pretty sure I'd be using 'qsort()' but I'm having extreme difficulties understanding the syntax for it. 我很确定我会使用'qsort()',但是在理解其语法方面遇到了极大的困难。 Some help with qsort and how do use it in this particular instance would be greatly appreciated. 我们将不胜感激qsort的一些帮助以及如何在此特定实例中使用它。

man 3 qsort() . man 3 qsort() If you read this, you will be able to use it. 如果阅读此内容,将可以使用它。 The only thing you need is a proper comparator function that returns the order of the two elements given as its arguments: 您唯一需要的是一个适当的比较器函数,该函数返回作为其参数给出的两个元素的顺序:

int comp_avg(const void *p1, const void *p2)
{
    const stuff *s1 = p1, *s2 = p2;
    return (s1->average > s2->average) - (s1->average < s2->average);
}

Then you can sort the array easily: 然后,您可以轻松地对数组进行排序:

qsort(
    everything,
    sizeof(everything) / sizeof(everything[0]),
    sizeof(everything[0]),
    comp_avg
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM