提示:文章
文章目录
前言
前期疑问:
本文目标:
一、背景
最近
二、
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);
总结
未完待续