题目描述
定义一个学生类Student,包含该学生的姓名、出生年、月、日 ,重定义 “-”号实现两个学生之间相差多少天的比较。并利用重载的“-”运算符,求所有学生中年龄相差最大的两个人的名字以及相差天数。 输入
第一行:输入所需要输入的学生个数;
第二行开始,依次输入每个学生的姓名、出生年、月、日。 输出 输出年龄相差最大的两个人的名字以及相差天数。样例输入
3
Tom 1995 1 1
Joe 1995 2 28
Jimmy 1996 1 8样例输出
Tom和Jimmy年龄相差最大,为372天
#include <bits/stdc++.h>
using namespace std;
class Date
{
private:
int y, m, d;
public:
Date() {}
void set_Date(int y, int m, int d)
{
this->y = y;
this->m = m;
this->d = d;
}
int compare(Date &a)
{
int t1 = 0, t2 = 0;
int leap[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int common[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0))
{
for (int i = 0; i < m - 1; i++)
{
t1 += leap[i];
}
t1 += d;
}
else
{
for (int i = 0; i < m - 1; i++)
{
t1 += common[i];
}
t1 += d;
}
if ((a.y % 4 == 0 && a.y % 100 != 0) || (a.y % 400 == 0))
{
for (int i = 0; i < a.m - 1; i++)
{
t2 += leap[i];
}
t2 += a.d;
}
else
{
for (int i = 0; i < a.m - 1; i++)
{
t2 += common[i];
}
t2 += a.d;
}
if (y == a.y)
{
return abs(t1 - t2);
}
else
{
int max, min;
if (y > a.y)
{
max = y;
min = a.y;
for (int i = max - min; i > 0; i--)
{
if ((min % 4 == 0 && min % 100 != 0) || (min % 400 == 0))
{
t1 += 366;
}
else
{
t1 += 365;
}
}
return t1 - t2;
}
else
{
max = a.y;
min = y;
for (int i = max - min; i > 0; i--)
{
if ((min % 4 == 0 && min % 100 != 0) || (min % 400 == 0))
{
t2 += 366;
}
else
{
t2 += 365;
}
}
return t2 - t1;
}
}
}
};
class Student
{
private:
string name;
Date birthday;
public:
Student() {}
void set(string n, int y, int m, int d)
{
birthday.set_Date(y, m, d);
name = n;
}
int operator-(Student &s)
{
int t;
t = birthday.compare(s.birthday);
return t;
}
void showname()
{
cout << name;
}
};
int main()
{
int t, y, m, d, day = 0, max = 0, s1 = 0, s2 = 1;
string name;
cin >> t;
Student *s = new Student[t];
for (int i = 0; i < t; i++)
{
cin >> name >> y >> m >> d;
s[i].set(name, y, m, d);
}
for (int i = 0; i < t - 1; i++)
for (int j = 1; j < t; j++)
{
day = s[i] - s[j];
if (day > max)
{
max = day;
s1 = i;
s2 = j;
}
}
s[s1].showname();
cout << "和";
s[s2].showname();
cout << "年龄相差最大,为" << max << "天。";
}