我必须使用qsort()
函数按板球运动员平均成绩的升序对他们进行排序,然后根据该函数打印所有详细信息。我不知道如何根据平均得分排序,然后根据它打印列表。
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
int compare(const void*a, const void*b)
{
return (*(int*)a - *(int*)b);
}
void main()
{
int i;
struct cricket
{
char name[20];
int age;
int no_test;
int avrun;
}
players[20] = {
"Virat Kohli", 25, 29, 94,
"Rohit Sharma", 26, 19, 86,
"Mahendra Singh Dhoni", 32, 40, 69,
"Gautum Gambhir", 29, 28, 90,
"Hardik Pandya", 27, 18, 59,
"Chris Gayle", 38, 50, 48,
"James Watson", 40, 54, 68,
"Brett Lee", 38, 53, 83,
"Suresh Raina", 32, 29, 59,
"Sachin Tendulkar", 40, 60, 95,
"Virendra Sehwag", 45, 55, 83
};
qsort(players,11,sizeof(cricket),compare);
for(i = 0; i < 11; i++)
{
printf("%s ", players[i].name);
printf("%d ", players[i].age);
printf("%d ", players[i].no_test);
printf("%d \n", players[i].avrun);
}
getch();
}
最佳答案
将void main()
更改为int main(void)
。What should main() return in C and C++?
You might not want to use conio.h
。struct cricket
的定义对compare()
应该是可见的,所以在该函数之前(就在头文件之后)移动它。
然后在结构定义的末尾需要一个分号。
现在需要声明数组的类型,如下所示:struct cricket players[20]
。
然后,您将收到以下警告:
警告:初始化项周围缺少大括号[-w缺少大括号]
关于你初始化玩家的方式。你需要这样做:
struct cricket players[20] = {
{"Virat Kohli", 25, 29, 94},
{"Rohit Sharma", 26, 19, 86},
...
};
然后,必须修复此错误:
错误:“cricket”未声明(首次在此函数中使用)
qsort(球员,11,板球,比较);
只需将
cricket
替换为struct cricket
。把所有的东西放在一起,你有:
#include <stdio.h>
#include <stdlib.h>
struct cricket {
char name[20];
int age;
int no_test;
int avrun;
};
int compare(const void*a, const void*b) {
return (*(int*)a - *(int*)b);
}
int main(void) {
int i;
// I changed the size of the array too, to 11.
struct cricket players[11] = {
{"Virat Kohli", 25, 29, 94},
{"Rohit Sharma", 26, 19, 86},
{"Mahendra Singh Dhoni", 32, 40, 69},
{"Gautum Gambhir", 29, 28, 90},
{"Hardik Pandya", 27, 18, 59},
{"Chris Gayle", 38, 50, 48},
{"James Watson", 40, 54, 68},
{"Brett Lee", 38, 53, 83},
{"Suresh Raina", 32, 29, 59},
{"Sachin Tendulkar", 40, 60, 95},
{"Virendra Sehwag", 45, 55, 83}
};
qsort(players,11,sizeof(struct cricket),compare);
for(i = 0; i < 11; i++) {
printf("%s ", players[i].name);
printf("%d ", players[i].age);
printf("%d ", players[i].no_test);
printf("%d \n", players[i].avrun);
}
return 0;
}
它将运行并产生毫无意义的输出。在compare函数中,应该考虑要对数组排序的字段。
了解这个问题中提到的内容,然后继续并修改比较函数。
关于c - 根据其元素之一对结构进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51131726/