加载中...

浙江理工大学入队200题——16B

问题 B: 零基础学C/C++171——年龄排序

题目描述

输入n个学生的信息,包括姓名、性别、出生年月。要求按年龄从小到大依次输出这些学生的信息。数据保证没有学生同年同月出生。

输入

第一行输入一个整数n表示学生人数(n<=100)
接下来n行,每一行依次输入学生的姓名、性别、出生年份、出生年月

输出

按年龄从小到大,一行输出一个学生的原始信息

样例输入

点击查看代码
5
John male 1999 12
David female 1999 8
Jason male 1998 11
Jack female 1998 8
Kitty female 2000 7

样例输出

点击查看代码
Kitty female 2000 7
John male 1999 12
David female 1999 8
Jason male 1998 11
Jack female 1998 8

题解

本题考查结构体,对于没有同年同月的两个人,我们是怎么比较的呢?
当然是先比较年,如果相同才比较月;也可以将月换算成(float)年。按照这个方式我们可以自定义sort一下,然后按顺序输出。
不清楚sort函数的建议学一下,一个非常nice的函数>https://www.cnblogs.com/AlvinZH/p/6784862.html<

代码(AC)

点击查看代码
#include <iostream> 
#include <string>
#include <algorithm>
using namespace std;
struct student
	{
		char name[50];
		char sex[10];
		int year;
		int month;
		float s;
	};
bool cmp(student a,student b)
	{
		return a.s>b.s;
	}
int main ()
{
	int n;
	scanf("%d",&n);
	struct student stu[n];
	for(int i=0;i<n;i++)
	{
		scanf("%s%s%d%d",&stu[i].name,&stu[i].sex,&stu[i].year,&stu[i].month);
		stu[i].s=(float)stu[i].year+(float)stu[i].month/12.0;
	}
	sort(stu,stu+n,cmp);
	for(int i=0;i<n;i++)
	{
		printf("%s %s %d %d\n",stu[i].name,stu[i].sex,stu[i].year,stu[i].month);
	}
	
	return 0;
}
posted @ 2022-10-30 09:48  shany212  阅读(80)  评论(0编辑  收藏  举报