题目是这样的
读入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
我的代码如下:
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
typedef struct student{
char name[10];
char ID[10];
int score;
}stu;
struct sturule
{
bool operator() (const student &a,const student &b)
{
return a.score < b.score;
}
};
int main(void)
{
int n;
cin >> n;
stu a[n];
for(int i=0;i<n;i++)
cin >> a[i].name >> a[i].ID >> a[i].score;
sort(a,a+n,sturule());
cout << a[n-1].name << " " << a[n-1].ID << endl;
cout << a[0].name << " " << a[0].ID << endl;
return 0;
}
做OJ题,几乎每次都不能一次性正确,错了有时候找不到问题,烦恼。
LZ,我运行你的代码
输入:
3
Joe Math990112 89
Mike CS991301 100
Mary EE990830 95
输出:
Mike CS991301
Joe Math990112Y
最后结尾多了一个Y,在Joe这一行数据中因为ID正好是10个字符把结构体中的char ID[10] 填满了,没有结束符,所以就接着往后输出将数字89当做字符‘Y’输出。
出现结束符,输出结束。
修改方法,将结构体中的字符加大一位:
typedef struct student{
char name[11];
char ID[11];
int score;
}stu;
该方法已测试成功。
另外,LZ定义变量时最好都有初始化,不然很多bug不好找。
可以考虑一下将字符数组换成string。
好早以前的作业题。有意思了。