使用函数完成学生信息处理

 一、问题

若已有四个学生的学号、班级、姓名、三门课程的成绩,在main函数中分别调用以下函数(1)和函数(2)实现相应功能,最后在main函数中输出排序后所有学生的信息。函数名等自行定义。
函数(1): 计算每个学生的总成绩;
函数(2): 按照班级从小到大、同一班级内按照姓名拼音字典顺序排序。

已有四个学生的信息如下,在程序中使用初始化完成,不需要由用户输入:
1001,11,Zhao,92.5,82.5,96
1002,12,Qian,82.5,87.5,93.5
1003,13,Sun,97,84.5,88.5
1004,12,Li,95.8,85.6,74.9

输出示例:
1001,11,Zhao,92.5,82.5,96.0,271.0
1004,12,Li,95.8,85.6,74.9,256.3
1002,12,Qian,82.5,87.5,93.5,263.5
1003,13,Sun,97.0,84.5,88.5,270.0

二、代码

#include <stdio.h>
#include <string.h>
#define MIN(i, j) (((i) < (j)) ? (i) : (j))

struct student {
    int id, c;
    float x, y, z;
    float sum;
    char name[233];
} stu[4];

int cmp(char s1[], char s2[]) {
    int l1 = strlen(s1), l2 = strlen(s2);
    for (int i = 0; i < MIN(l1, l2); i++) {
        if (s1[i] > s2[i])
            return 1;
        else if (s1[i] < s2[i])
            return -1;
    }
    if (l1 == l2)
        return 0;
    else if (l1 > l2)
        return 1;
    else
        return -1;
}

void swap(struct student* a, struct student* b) {
    struct student c;
    c = *a;
    *a = *b;
    *b = c;
}

void sort() {
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4 - i - 1; j++) {
            if (stu[j].c > stu[j + 1].c || (stu[j].c == stu[j + 1].c && cmp(stu[j].name, stu[j + 1].name) > 0)) {
                swap(&stu[j], &stu[j + 1]);
            }
        }
    }
}

float sum(int i) {
    return stu[i].x + stu[i].y + stu[i].z;
}

int main() {
    stu[0].c = 11;
    stu[0].id = 1001;
    stu[0].x = 92.5;
    stu[0].y = 82.5;
    stu[0].z = 96;
    strcpy(stu[0].name, "Zhao");

    stu[1].c = 12;
    stu[1].id = 1002;
    stu[1].x = 82.5;
    stu[1].y = 87.5;
    stu[1].z = 93.5;
    strcpy(stu[1].name, "Qian");

    stu[2].c = 13;
    stu[2].id = 1003;
    stu[2].x = 97;
    stu[2].y = 84.5;
    stu[2].z = 88.5;
    strcpy(stu[2].name, "Sun");

    stu[3].c = 12;
    stu[3].id = 1004;
    stu[3].x = 95.8;
    stu[3].y = 85.6;
    stu[3].z = 74.9;
    strcpy(stu[3].name, "Li");

    stu[0].sum = sum(0);
    stu[1].sum = sum(1);
    stu[2].sum = sum(2);
    stu[3].sum = sum(3);

    sort();

    for (int i = 0; i < 4; i++)
        printf("%d,%d,%s,%.1f,%.1f,%.1f,%.1f\n", stu[i].id, stu[i].c,stu[i].name, stu[i].x, stu[i].y, stu[i].z, stu[i].sum);
    return 0;
}

三、tips

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值