void sortByScore(struct STI *s, int Cnt) //按成绩排序
{
int i,j;
struct STI tmp; //此处注意tmp的类型为struct STI
for(i = 0; i < Cnt; i++)
{
for(j = i; j < Cnt; j++)
{
if(s[i].score < s[j].score ) //score为double型,但是直接进行比较,需查询
//double类型数据存储的数据是不精确的存储。这是由于计算机表示浮点数的方法造成的精度缺陷,所以,在比较时,一般通过判断两数差与一个精度值的大小,来确定两数的大小,这个精度值由使用者根据情况自行确定
{
tmp = s[i]; // C语言允许在结构体实例之间直接赋值!
s[i] = s[j]; // struct STI a = {…};
s[j] = tmp; // struct STI b;
// b = a; // 这就可以完成将a的所有成员数据,赋值给b的所有成员
}
}
}
}
void sortById(struct STI *s, int Cnt) //按学号排序
{
int i,j;
struct STI tmp; //此处注意tmp的类型为struct STI
for(i = 0; i < Cnt; i++)
{
for(j = i; j < Cnt; j++)
{
if(strcmp(s[i].id, s[j].id) > 0) //if(strcmp(s[i].id < s[j].id)) 错误形式
//因为id为char型,故不能直接进行比较,需使用strcmp()函数进行比较
{
tmp = s[i];
s[i] = s[j];
s[j] = tmp;
}
}
}
}
void main(void)
{
struct STI st[20]; //st表示student,st的数据类型为struct STI,此处假设有20个学生
int stCount = 0;
inputStudentsInformation(st, &stCount); //st <=> &st[0]
showStudentsInformation(st, stCount);
printf("按学号升序排序后结果如下:\n");
sortById(st, stCount);
showStudentsInformation(st, stCount);
printf("按成绩降序排序后结果如下:\n");
sortByScore(st, stCount);
showStudentsInformation(st, stCount);
}
输出结果如下:

|