Вопрос

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. 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. Some help with qsort and how do use it in this particular instance would be greatly appreciated.

Это было полезно?

Решение

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 с атрибуция
Не связан с StackOverflow
scroll top