【发布时间】:2020-05-31 06:37:57
【问题描述】:
我有一个程序旨在接收由他们的姓名和 3 个测试分数组成的 n 个学生结构,并且必须使用 qsort() 根据他们的总分按降序输出它们。虽然我已经能够对它们进行排序,但它们仅按它们的第一个值排序。
有没有办法对每个学生的值求和然后使用 qsort?我尝试编辑元素数量的值以及比较函数的指针,但没有任何效果
#include <cstdlib>
#include <iostream>
using namespace std;
typedef struct {
char name[16];
int chineseScore;
int mathScore;
int englishScore;
int totalScore;
} student;
int compare(const void* p1, const void* p2) {
student *a = (student *)p1;
student *b = (student *)p2;
return (a - b);
}
int main() {
//gets input
int n;
do{
cin >> n;
}while (n < 1 || n > 10);
student stud[n];
for (int i = 0; i < n; i++){
cin >> stud[i].name >> stud[i].chineseScore >> stud[i].mathScore >> stud[i].englishScore;
stud[i].totalScore = stud[i].chineseScore + stud[i].mathScore + stud[i].englishScore;
}
//sorts array with qsort()
qsort(stud, n, sizeof(student), compare);
//prints result
for (int i = 0; i < n; i++){
cout << stud[i].name << ' '<< stud[i].chineseScore <<' '<< stud[i].mathScore <<' '<< stud[i].englishScore<< endl;
}
return 0;
}
【问题讨论】:
-
作为新用户,请拨打tour阅读How to Ask。关于你的问题,很明显你需要调整你的
compare()函数,所以我不确定你在问什么。顺便说一句:编译带有警告并提交您的代码(一旦它工作)在 codereview.stackexchange.com 上进行审查。有几件事情迟早会导致问题。