题目要求如下:
由于会输入小白鼠的体重和颜色,因此可以使用1个结构体将其封装起来。
之后调用排序函数按照体重大小进行排序,再输出其对应的颜色即可。
下面是实现的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int weight;
char color[10];
} Rat;
int rat_compare(const void *p1, const void *p2) {
Rat *a = (Rat *) p1;
Rat *b = (Rat *) p2;
return (b->weight) - (a->weight);
}
int main(int argc, char **argv) {
int num;
Rat rats[100] = {0};
while (scanf("%d", &num) != EOF) {
for (int j = 0; j < num; ++j) {
scanf("%d %s", &rats[j].weight, &rats[j].color);
}
qsort(rats, num, sizeof(rats[0]), rat_compare);
for (int i = 0; i < num; ++i) {
printf("%s\n", rats[i].color);
}
}
return 0;
}
最后是通过后的结果: