学生生日差值计算(运算符重载)
时间限制: 1 Sec 内存限制: 128 MB提交: 496 解决: 283
[ 提交][ 状态][ 讨论版]
题目描述
定义一个学生类Student,包含该学生的姓名、出生年、月、日 ,重定义 “-”号实现两个学生之间相差多少天的比较。并利用重载的“-”运算符,求所有学生中年龄相差最大的两个人的名字以及相差天数。
输入
第一行:输入所需要输入的学生个数;
第二行开始,依次输入每个学生的姓名、出生年、月、日。
输出
输出年龄相差最大的两个人的名字以及相差天数。
样例输入
3
Tom 1995 1 1
Joe 1995 2 28
Jimmy 1996 1 8
样例输出
Tom和Jimmy年龄相差最大,为372天。
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
class Student
{
private:
string name;
int y,m,d,
totalDay;
public:
Student():name("Mr.ERROR"),y(0),m(0),d(0){}
Student(string n,int a,int b,int c):name(n),y(a),m(b),d(c){totalDay = getDays();}
int getDays()
{
int day=0,i;
int a[12]={31,28,31,30,31,30,31,31,30,31,30,31},
b[12]={31,29,31,30,31,30,31,31,30,31,30,31};
if(Isluner())
{
for(i=1;i<m;i++)
day+=b[i-1];
}
else
{
for(i=1;i<m;i++)
day+=a[i-1];
}
day+=d;
return day;
}
bool Isluner()
{
return ((y%400==0)||(y%4==0&&y%100!=0));
}
bool Isluner(int _y)
{
return ((_y%400==0)||(_y%4==0&&_y%100!=0));
}
int operator - (Student &b)
{
int luner=0;
int toty=0;
if(b.y==y)
{
if(totalDay-b.totalDay>0)
return(totalDay-b.totalDay);
else
return(b.totalDay-totalDay);
}
else if(b.y>y)
{
for(int year=y;year<b.y;year++)
{
if(Isluner(year))
luner++;
}
toty=b.y-y;
return(b.totalDay-totalDay+toty*365+luner);
}
else if(b.y<y)
{
for(int year=b.y;year<y;year++)
{
if(Isluner(year))
luner++;
}
toty=y-b.y;
return(totalDay-b.totalDay+toty*365+luner);
}
return -1;
}
friend void getmaxdis(Student*st,int n);
};
void getmaxdis(Student*st,int n)
{
int Max=0;
string n1,n2;
for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(Max<st[j]-st[i])
{
Max=st[j]-st[i];
n1=st[i].name;
n2=st[j].name;
}
}
}
cout<<n1<<"和"<<n2<<"年龄相差最大,为"<<Max<<"天。"<<endl;
}
int main()
{
string name;
int y,m,d;
int n;
cin>>n;
Student *st=new Student [n];
for(int i=0;i<n;i++)
{
cin>>name>>y>>m>>d;
st[i]=Student(name,y,m,d);
}
getmaxdis(st,n);
delete [] st;
return 0;
}