1004 成绩排名 (20)

发表在专栏“PAT乙级题目详解”,并在持续更新中。

https://blog.csdn.net/column/details/23947.html


读入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

分析:

1.这道题主要考察结构体的排序,排序函数如下:

//对结构体中某一元素排序
bool cmp(Student a, Student b)
{
	if (a.score < b.score)
	{
		return true;
	}
	else
	{
		return false;
	}
}

使用时,先引用头文件

#include <algorithm>

在主函数中使用sort方法

sort(mystudent, mystudent + n, cmp);

完整代码如下(此代码在本地编译器可以通过,但是没有在刷题网站上通过!!!

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
//结构体定义
struct Student
{
	string name;//姓名
	string num;//学号
	int score;//成绩
};

//对结构体中某一元素排序
bool cmp(Student a, Student b)
{
	if (a.score < b.score)
	{
		return true;
	}
	else
	{
		return false;
	}
}

int main()
{

	int n;//一共有n个学生
	cin >> n;
	struct Student mystudent[1000];
	for (int i = 0; i < n; i++)
	{
		cin >> mystudent[i].name;
		cin >> mystudent[i].num;
		cin >> mystudent[i].score;
	}
	sort(mystudent, mystudent + n, cmp);

	cout << mystudent[n - 1].name << " " << mystudent[n - 1].num << endl;
	cout << mystudent[0].name << " " << mystudent[0].num << endl;
	system("pause");
	return 0;
}

上面代码在本地编译器可以通过,但是没有在刷题网站上通过!!!刷题遇到这种情况应该是最无奈的,因为根本就不知道错在哪里了,只能是一点点的推理,慢慢的查找。

想来想去还是因为对sort这个方法应用的不熟,所以改成暴力排序(最最最古老的排序),然后就通过了。。。

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
//结构体定义
struct Student
{
	string name;//姓名
	string num;//学号
	int score;//成绩
};

int main()
{
	
	int n;//一共有n个学生
	cin >> n;
	struct Student mystudent[1000];
	for (int i = 0; i < n; i++)
	{
		cin >> mystudent[i].name;
		cin >> mystudent[i].num;
		cin >> mystudent[i].score;
	}

	int max = 0;//记录成绩最高的学生在数组中的位置
	int maxNum = mystudent[0].score;//记录最好的成绩
	int min = 0;//记录成绩最低的学生在数组中的位置
	int minNum = mystudent[0].score;//记录最低成绩
	
	for (int i = 1; i < n; i++)
	{
		//找一个最小值
		if (mystudent[i].score < minNum)
		{
			min = i;
			minNum = mystudent[i].score;
		}
		//找一个最大值
		if (mystudent[i].score > maxNum)
		{
			max = i;
			maxNum = mystudent[i].score;
		}
	}

	cout << mystudent[max].name << " " << mystudent[max].num << endl;
	cout << mystudent[min].name << " " << mystudent[min].num << endl;
	//system("pause");
	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值