题目描述
定义一个学生类Student,包含该学生的姓名、出生年、月、日 ,重定义 “-”号实现两个学生之间相差多少天的比较。并利用重载的“-”运算符,求所有学生中年龄相差最大的两个人的名字以及相差天数。
输入
第一行:输入所需要输入的学生个数;
第二行开始,依次输入每个学生的姓名、出生年、月、日。
输出
输出年龄相差最大的两个人的名字以及相差天数。
//
输入样例:
3
Tom 1995 1 1
Joe 1995 2 28
Jimmy 1996 1 8
输出样例:
Tom和Jimmy年龄相差最大,为372天。
AC代码:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class Student
{
public:
Student(string name, int year, int month, int day) : name(name), year(year), month(month), day(day) {}
// 重载 "-" 运算符,计算两个学生出生日期相差的天数
int operator-(const Student &other) const
{
return abs(daysSinceEpoch() - other.daysSinceEpoch());
}
const string &getName() const
{
return name;
}
private:
string name;
int year;
int month;
int day;
// 辅助函数,计算自 xx 年 x 月 x 日以来的天数
int daysSinceEpoch() const
{
const int daysPerYear = 365;
int days = year * daysPerYear;
days += (year - 1) / 4; // 闰年多加一天
days -= (year - 1) / 100; // 但是每100年不是闰年
days += (year - 1) / 400; // 但是每400年又是闰年
days += daysInMonth(month, year);
days += day - 1;
return days;
}
// 辅助函数,计算某年某月的天数
int daysInMonth(int month, int year) const
{
const int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int days = 0;
for (int i = 0; i < month - 1; i++)
{
days += daysInMonth[i];
}
// int days = daysInMonth[month - 1];
if (month == 2 && isLeapYear(year))
{
days++;
}
return days;
}
// 辅助函数,判断是否是闰年
bool isLeapYear(int year) const
{
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
};
int main()
{
int n;
cin >> n; // 输入学生个数
vector<Student> students;
for (int i = 0; i < n; ++i)
{
string name;
int year, month, day;
cin >> name >> year >> month >> day;
students.push_back(Student(name, year, month, day));
}
// 找出年龄相差最大的两个人
int maxDifference = 0;
pair<string, string> maxDifferenceNames;
for (int i = 0; i < students.size(); ++i)
{
for (int j = i + 1; j < students.size(); ++j)
{
int difference = students[i] - students[j];
if (difference > maxDifference)
{
maxDifference = difference;
maxDifferenceNames = make_pair(students[i].getName(), students[j].getName());
}
}
}
// 输出结果
cout << maxDifferenceNames.first << "和" << maxDifferenceNames.second << "年龄相差最大,为" << maxDifference << "天。" << endl;
return 0;
}