HJ68 成绩排序

提示:文章

文章目录

前言

前期疑问:
本文目标:


一、背景

最近

二、

2.1 代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct StudentInfo
{
    char name[100];
    int score;
}StuInfo;

int compareUpper(const void* a, const void* b)
{
    return ((struct StudentInfo*)a)->score - ((struct StudentInfo*)b)->score;
}

int compareLower(const void* a, const void* b)
{
    return ((struct StudentInfo*)b)->score - ((struct StudentInfo*)a)->score;
}

int main() {
    int count = 0;
    int format = 0;
    while (scanf("%d", &count) != EOF) { // 注意 while 处理多个 case
        // 64 位输出请用 printf("%lld") to 
        scanf("%d", &format);
        struct StudentInfo stuInfo[count];
        memset(stuInfo, 0, sizeof(struct StudentInfo) * count);
        for(int i = 0; i < count; i++)
        {
            char name[100] = {'\0'};
            int score;
            scanf("%s %d", name, &score);
            strcpy(stuInfo[i].name, name);
            stuInfo[i].score = score; 
        }
        if(format == 0)
        {
            qsort(stuInfo, count, sizeof(struct StudentInfo), compareLower);
        }else {
            qsort(stuInfo, count, sizeof(struct StudentInfo), compareUpper);
        }
        

        for(int i = 0; i < count; i++)
        {
            printf("%s %d\n", stuInfo[i].name, stuInfo[i].score);
        }
    }

    return 0;
}

一次通过,没有看解答,也许解答有更好的解决办法。

一、其中写的比较纠结的就是结构的使用,我把结构体写成这样

struct StudentInfo
{
    char name[100];
    int score;
}StuInfo;

那其中StuInfo的作用是什么?

二、
strcpy使用了两个参数,srcStr和dstStr。我一开始还以为是三个参数,写错了。

三、
scanf(“%s %d”, name, &score);这边一开始写成了scanf(“%s,%d”, name, &score);读取数据有问题。

四、
局部变量忘了清零
memset(stuInfo, 0, sizeof(struct StudentInfo) * count);


总结

未完待续

  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值