有5名学生保存在结构体数组中,编程按学生的成绩升序排序,按学生的姓名降序排序,按年龄从低到高排序

来源:互联网 发布:阿里云配置二级域名 编辑:程序博客网 时间:2024/05/05 15:46

typedef struct stu{

    

   char name[20];//存储姓名

   int age;//年龄

   float score;//

    

}Stu;

void sortScore(Stu stu[],int n);

void sortName(Stu stu[],int n);

void outPut(Stu stu[],int n);

void sortScore(Stu stu[],int n){

   Stu temp = {};

   for (int i =0; i < n - 1; i++) {

       for (int j =0; j < n - 1 - i; j++) {

           if (stu[j].score > stu[j+1].score) {

                temp = stu[j];

                stu[j] = stu[j+1];

                stu[j+1] = temp;

            }

            

        }

    }

    printf("按分数排序后:\n");

   outPut(stu, n);

}

void sortName(Stu stu[],int n){

   Stu temp ={} ;

   for (int i =0; i < n - 1; i++) {

       for (int j =0; j < n - 1 - i; j++) {

           if (strcmp(stu[j].name, stu[j+1].name) >0) {

                temp = stu[j];

                stu[j] = stu[j+1];

                stu[j+1] = temp;

                


            }

            

        }

    }

    printf("按名字排序后:\n");

   outPut(stu, n);

}

void outPut(Stu stu[],int n){

    

   for (int i =0; i < n ; i++) {

       printf("%s " ,stu[i].name);

       printf("%.2f " ,stu[i].score);

       printf("%d " ,stu[i].age);

       printf("\n");

    }   

}

int main(int argc,const char * argv[])

{

    //1.5名学生保存在结构体数组中,编程按学生的成绩升序排序,按学生的姓名降序排序,按年龄从低到高排序

   Stu b[5] = {

        {"xiaomeng",32,100},

        {"xiaoshuaishuai",36,88},

        {"xiaomingming",28,99},

        {"xiaoguangguang",35,77},

        {"xiaohonghong",39,66}

    };

   sortScore(b, 5);//按分数排列

   sortName(b, 5);//按名字排列

    return0;

}


0 0