ghjhkniob
2020-05-18 17:22
采纳率: 93.3%
浏览 1.3k

C语言有10个学生,每个学生数据包括学号、姓名和成绩,前8个学生的数据采用初始化,后2个学生键盘输入?

63.
编程题
有10个学生,每个学生数据包括学号、姓名和成绩,前8个学生的数据采用初始化,后2个学生键盘输入。编写一个程序,将这10个学生的信息按成绩由高到低的顺序排序并保存后输出所有学生的全部信息。
请认真测试程序的正确性。将源代码以文本方式提交,不要直接提交文件。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • Huoon 2020-05-20 22:35
    已采纳
    
    #include <random>
    #include <stdio.h>
    #define STUDENT_COUNT  10
    #define NAME_LEN  64
    
    struct Student
    {
        int no;
        char name[NAME_LEN];
        int score;
    };
    
    void sort(struct Student* students, int count)
    {
        int i = 0;
        int j = 0;
        struct Student temp;
        for (i = 0; i < count; i++)
        {
            for (j = 0; j < count - 1; j++)
            {
                if (students[j].score < students[j + 1].score)
                {
                    temp = students[j];
                    students[j] = students[j + 1];
                    students[j + 1] = temp;
                }
            }
        }
    }
    
    void main()
    {
        int i = 0;
        const char* name_prefix = "name";
        struct Student* students = (struct Student*)malloc(sizeof(struct Student) * STUDENT_COUNT);
    
        for (i = 0; i < STUDENT_COUNT - 2; i++)
        {
            students[i].no = i;
    
            memset(students[i].name, 0, NAME_LEN);
            memcpy(students[i].name, name_prefix, strlen(name_prefix));
            students[i].name[strlen(name_prefix)] = i + '0';
    
            students[i].score = rand() % 100;
        }
    
        printf("输入学号,姓名,分数:\n");
        scanf("%d%s%d", &students[i].no, students[i].name, &students[i].score);
        i++;
    
        printf("输入学号,姓名,分数:\n");
        scanf("%d%s%d", &students[i].no, students[i].name, &students[i].score);
    
    
        sort(students, STUDENT_COUNT);
    
        for (i = 0; i < STUDENT_COUNT; i++)
        {
            printf("no:%d  name:%s  score:%d\n", students[i].no, students[i].name, students[i].score);
        }
    
        getchar();
    }
    
    点赞 打赏 评论