错误排序结构时间。程序使用 struct 和 qsort 来接受和存储用户输入;名字、姓氏、国家和时间。输出应使用 qsort 按时排序,例如
输入
BEKELE Tariku ETH 27:31.43
RUPP 盖伦美国 27:30.90
法拉莫国标 27:30.42
输出
法拉莫国标 27:30.42
RUPP 盖伦美国 27:30.90
BEKELE Tariku ETH 27:31.43
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct olympics {
//char athlete[25];
char fname[15];
char lname[15];
char country[5];
float time;
};
/* qsort struct comparision function (time float field) */
int struct_cmp_by_time(const void *a, const void *b)
{
struct olympics *ia = (struct olympics *)a;
struct olympics *ib = (struct olympics *)b;
return (int)(60.f*ia->time - 60.f*ib->time);
}
/* struct array printing function */
void print_struct_array(struct olympics *array, size_t len)
{
size_t i;
for(i=0; i<len; i++)
printf("%s %s %s \t %.2f\n", array[i].fname, array[i].lname, array[i].country, array[i].time);
puts("****");
}
/* sorting structs using qsort() */
void sort_structs_time(void)
{
struct olympics structs[] = {
scanf("%s %s %s %.2f\n", fname, lname, country, &time)
};
size_t structs_len = sizeof(structs) / sizeof(struct olympics);
puts("**** Athletes finishing time...");
/* print original struct array */
print_struct_array(structs, structs_len);
/* sort array using qsort functions */
qsort(structs, structs_len, sizeof(struct olympics), struct_cmp_by_time);
/* print sorted struct array */
print_struct_array(structs, structs_len);
}
/* call to the function) */
int main()
{
/* run the function */
sort_structs_time();
return 0;
}