方法一:用结构体
#include <iostream>
using namespace std;
struct Date{ //定义结构体Date
int y; //year
int m; //month
int d; //day
};
Date input()
{
//int y,m,d
Date d;
cout<<"input a date:";
cin>>d.y>>d.m>>d.d;
return d;
}
int dayofmonth(int m,int y) //定义dayofmonth函数
{
int maxday;
if(m==4||m==6||m==9||m==11) //4 6 9 11月最大天数为30
{
maxday=30;
}
else if(m==2) //计算2月份的天数要先判断是否为闰年
{
if(y%4==0&&y%100!=0||y%400==0) //如果是闰年
{
maxday=29; //2月有29天
}
else maxday=28; //如果不是 2月有28天
}
else maxday=31; //1 3 5 7 8 10 12最大天数为31天
return maxday;
}
Date nextdate(Date d) //计算下一天
{
++d.d;
int maxday;
maxday=dayofmonth(d.m,d.y);
if(d.d>maxday)
{
d.d=1;
++d.m;
if(d.m>12)
{
d.m=1;
++d.y;
}
}
return d;
}
void output(Date d) //输出函数
{
cout<<d.y<<"-"<<d.m<<"-"<<d.d<<endl;
}
int main()
{
//input a date
Date d=input();
//calculate the next day of that date
d=nextdate(d);
//output the result
cout<<"明天是:"<<endl;
output(d);
}
方法二:一般方法
#include <iostream>
using namespace std;
int main()
{
//input a date
int y,m,d;
cout<<"input a date:";
cin>>y>>m>>d;
//calculate the next day
//increase d
++d;
//calculate days of that month
//4,6,9,11:30 days
//2: 28 or 29 days
//others:31 days
int maxday;
if(m==4||m==6||m==9||m==11)
{
maxday=30;
}
else if(m==2)
{
if(y%4==0&&y%100!=0||y%400==0)
{
maxday=29;
}
else maxday=28;
}
else maxday=31;
//check if d is greater than days of that month
if(d>maxday)
{
d=1;
++m;
}
if(m>12)
{
m=1;
++y;
}
//increase m,d reset to 1
//check if m is greater than 12:increase y,m reset to 1
//output the result
cout<<y<<'-'<<m<<'-'<<d<<endl;
}