谢谢。再写了一个
[C] 纯文本查看 复制代码
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#define NAME_LEN 128
#define NUM 5
typedef struct {
char name[NAME_LEN];
int height;
int weight;
int score;
} Stu;
enum choices {name=1, height, weight, score};
void scanf_stu(Stu *stu);
enum choices input_choice(void);
void printf_stu(Stu *stu);
void sort_general(enum choices choice, Stu *stu);
bool compare(enum choices choice,Stu *stu, int i, int j);
void swap_stu(Stu *stui, Stu *stuj);
int main(int argc, char *argv[])
{
Stu stu[NUM];
// 要求用户输入结构体数组
scanf_stu(stu);
printf_stu(stu);
// 要求用户输入排序的依据
enum choices choice=input_choice();
// 通用排序函数
sort_general(choice, stu);
switch (choice) {
case name:
printf("按名字升序排序\n");
printf_stu(stu);
break;
case height:
printf("按身高升序排序\n");
printf_stu(stu);
break;
case weight:
printf("按体重升序排序\n");
printf_stu(stu);
break;
case score:
printf("按分数升序排序\n");
printf_stu(stu);
break;
}
return 0;
}
/*要求用户输入结构体数组*/
void scanf_stu(Stu *stu)
{
int i=0;
for (;i<NUM;i++) {
printf("请输入第%d位同学的名字、身高、体重、分数等信息:", i+1);
scanf("%s %d %d %d", &((stu+i)->name), &((stu+i)->height), &((stu+i)->weight), &((stu+i)->score));
}
}
/*要求用户输入排序的依据*/
enum choices input_choice(void)
{
int temp;
do {
printf("请输入排序的依据\n1--name;2--height;3--weight;4--score:");
scanf("%d", &temp);
} while (temp<name || temp>score);
return (enum choices)temp;
}
/*打印结构体数组*/
void printf_stu(Stu *stu)
{
int i=0;
for (i=0;i<NUM;i++) {
printf("%-8s %6d %6d %7ld\n", (stu+i)->name, (stu+i)->height, (stu+i)->weight, (stu+i)->score);
}
}
/*通用排序函数,冒泡排序*/
void sort_general(enum choices choice, Stu *stu)
{
int i=0,j;
for (;i<NUM-1;i++) {
for (j=i+1;j<NUM;j++) {
// 返回数组相邻两个结构体的比较结果
if (compare(choice, stu, i, j)) {
// 交换对应的结构体
swap_stu((stu+i), stu+j);
}
}
}
}
/*返回数组相邻两个结构体的比较结果*/
bool compare(enum choices choice,Stu *stu, int i, int j)
{
int result;
switch(choice) {
case name:
result = strcmp(((stu+i))->name, (stu+j)->name)>0;
break;
case height:
result = (stu+i)->height > (stu+j)->height;
break;
case weight:
result = (stu+i)->weight > (stu+j)->weight;
break;
case score:
result = (stu+i)->score > (stu+j)->score;
break;
}
return result;
}
/*升序排列时,当元素的结构体小于前面,交换对应的结构体*/
void swap_stu(Stu *stui, Stu *stuj)
{
Stu temp=*stui;
*stui=*stuj;
*stuj=temp;
} |