Description
小明的弟弟上小学了,每次刚入学就想知道什么时候放假,但是每学期开学的日子和每学期的有效天数都不一样,请你编程帮他计算放假日期。
Input
第一行输入开学的年月日,以空格隔开;第二行输入本学期的有效天数
Output
输出计算后得到的放假日期,格式为年/月/日。
Sample Input
2008 2 29
140
Sample Output
2008/7/18
代码:
#include <iostream>
using namespace std;
class Date
{
public:
void input(int y,int m,int d);
friend Date operator+(Date &c,int &day);
void display();
private:
int year;
int month;
int day;
};
void Date::input(int y,int m,int d)
{
year=y;
month=m;
day=d;
}
Date operator+(Date &c,int &day)
{
Date d;
int year,month,days;
year=c.year;
month=c.month;
days=c.day;
int i;
for(i=1; i<=day; i++)
{
days=days+1;
if(month==1||month==3||month==5||month==7||month==8||month==10||month==12)
{
if(days==32)
{
month=month+1;
days=1;
}
if(month==13)
{
year=year+1;
month=1;
}
}
if(month==2)
{
if(((year%4==0&&year%100!=0)||year%400==0))
{
if(days==30)
{
days=1;
month=month+1;
}
}
else
{
if(days==29)
{
days=1;
month=month+1;
}
}
}
if(month==4||month==6||month==9||month==11)
{
if(days==31)
{
month=month+1;
days=1;
}
if(month==13)
{
year=year+1;
month=1;
}
}
}
d.year=year;
d.month=month;
d.day=days;
return d;
}
void Date::display()
{
cout<<year<<"/"<<month<<"/"<<day<<endl;
}
int main()
{
Date date1,date2;
int y,m,d;
int day;
cin>>y>>m>>d;
date1.input(y,m,d);
cin>>day;
date2=date1+day;
date2.display();
return 0;
}
运行结果:
学习心得:
开始写的时候把if(month==1||month==3||month==5||month==7||month==8||month==10||month==12)和if(month==4||month==6||month==9||month==11)都只写了一个month,结果运行的时候结果不对,改了好多地方,还是不对,后来就把month都加上了才对的。