【Problem Description】
Design a program to calculate backward a specific date n days after a specified date.
【Input form】
-
The input is a string str of length 8 and a positive integer n. The first four digits of str represent the year, and the last four digits represent the month and day.
[Output form]
-
When the calculated year is greater than 4 digits, output "out of limitation!", otherwise output an 8-digit specific date.
[Sample input 1]
00250709 60000
[Sample output 1]
01891017
[Sample input 2]
19310918 5080
[Sample output 2]
19450815
[Sample input 3]
99980208 999
[Sample input 3]
out of limitation!
[Sample description]
-
The date must be represented by 8 digits. If the year, month and day are not long enough, the prefix character '0' must be added.
-
Note that the number of days in February is different between leap years and normal years.
-
Pay attention to determine whether the output information meets the requirements.
[The complete code is as follows]
#include<iostream>
#include<string.h>
using namespace std;
class Calculate
{
public:
Calculate(int years,int months,int days,int ns):year(years),month(months),day(days),n(ns)
{
}
bool Judge();//判断是否为闰年
void AddOne();
void AddDay();
void show();
private:
int year;
int month;
int day;
int n;
};
bool Calculate::Judge()
{
if((year%400==0)||(year%100!=0&&year%4==0))
return true;
else
return false;
}
void Calculate::AddOne()
{
if((month==1||month==3||month==5||month==7||month==8||month==10)&&(day==31))
{
day=1;
month+=1;
}
else if((month==4||month==6||month==9||month==11)&&(day==30))
{
day=1;
month+=1;
}
else if(month==12&&day==31)
{
day=1;
month=1;
year+=1;
}
else if(month==2&&day==29&&Judge())
{
day=1;
month+=1;
}
else if(month==2&&day==28&&!Judge())
{
day=1;
month+=1;
}
else
{
day+=1;
}
}
void Calculate::AddDay()
{
for(int i=0;i<n;i++)
{
AddOne();
}
if(year>9999)//判断推算出的年份大于4位数
{
cout<<"out of limitation!"<<endl;
}
else
{
show();
}
}
void Calculate::show()
{
cout<<year<<month<<day<<endl;
}
int main()
{
string str;
int n;
cin>>str;
cin>>n;
//把字符串里的日期信息转化为数字,方便后面的运算
int year = 1000 * (str[0] - 48) + 100 * (str[1] - 48) + 10 * (str[2] - 48) + (str[3] - 48);
// cout<<year<<endl;
int month = 10 * (str[4] - 48) + (str[5] - 48);
/// cout<<month<<endl;
int day = 10 * (str[6] - 48) + (str[7] - 48);
// cout<<day<<endl;
Calculate t(year,month,day,n);
t.AddDay();
return 0;
}