1004 成绩排名 (20)(20 分)
读入n名学生的姓名、学号、成绩,分别输出成绩最高和成绩最低学生的姓名和学号。
输入格式:每个测试输入包含1个测试用例,格式为
第1行:正整数n
第2行:第1个学生的姓名 学号 成绩
第3行:第2个学生的姓名 学号 成绩
... ... ...
第n+1行:第n个学生的姓名 学号 成绩
其中姓名和学号均为不超过10个字符的字符串,成绩为0到100之间的一个整数,这里保证在一组测试用例中没有两个学生的成绩是相同的。
输出格式:对每个测试用例输出2行,第1行是成绩最高学生的姓名和学号,第2行是成绩最低学生的姓名和学号,字符串间有1空格。
输入样例:
3
Joe Math990112 89
Mike CS991301 100
Mary EE990830 95
输出样例:
Mike CS991301
Joe Math990112
解析
这题只是考了c语言语法知识,不怎么难。 (后面写我踩的坑)
完整代码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define maxsize 15
struct student{
char name[maxsize];
char number[maxsize];
int score;
};
int main()
{
int student_number = 0;
int i = 0;
scanf("%d", &student_number);
struct student **list = (struct student **)malloc(sizeof(struct student *)*student_number);
for(i=0;i<student_number;i++){
*(list+i) = (struct student *)malloc(sizeof(struct student));
}
for (i = 0; i<student_number; i++) {
scanf("%s",(*(list + i))->name);
scanf("%s",(*(list + i))->number);
scanf("%d",&(*(list + i))->score);
}
int max = 0;
int min = 0;
for (i = 1; i<student_number; i++) {
int now_score = (*(list + i))->score;
if (now_score >(*(list + max))->score)
max = i;
if ((*(list + min))->score > now_score)
min = i;
}
printf("%s %s\n", (*(list + max))->name, (*(list + max))->number);
printf("%s %s", (*(list + min))->name, (*(list + min))->number);
for(i=0;i<student_number;i++){
free(*(list+i));
}
free(list);
return 0;
}
坑:
①姓名和学号的长度是1-10个字符,所以不能用char [10]来存储,而要用char [15]。
②在gcc里,student是不用用来声明的,要用struct student
③typedef struct student{
char name[maxsize];
char number[maxsize];
int score;
};
就算你用了typedef,student还是不能用来声明。c语言有些忘了,google试试。(待跟新)
update
Difference between ‘struct’ and ‘typedef struct’ in C++?
Why should we typedef a struct so often in C?
上面两个回答给出了答案。(我翻译下高票回答)
一:
C标准(C89 §3.1.2.3, C99 §6.2.3, and C11 §6.2.3)要求为不同的标识符分为不同的作用域.其中包括tag identical (struct / union /enum)和 ordinary identical (typedef ……)
如果你这样声明
struct Foo{.....};
Foo x
你会得到编译错误(没有声明Foo类型),因为Foo只在tag namespace内被定义.
所以你必须这样声明
struct Foo x;
每次你想声明Foo类型,你必须写成 struct Foo,但是这样很麻烦,所以你可以加上typedef
struct Foo { ... };
typedef struct Foo Foo;
现在struct Foo(它现在在tag namespace)和Foo(在ordinary identical namespace)都是指向同一个结构体。这样,你就能使用Foo啦,而不用加上关键词struct
typedef struct Foo { ... } Foo;
这只是声明和typedef的缩写
typedef struct { ... } Foo;
最后,声明一个匿名结构体并typedef,这样构造,tag namespace里没有声明(因为是匿名声明的),只有typedef作用域有一个名字。这意味这你不能前向声明。如果你想要前向声明,你必须在tag namespace里给他一个名字