这题我采用的方法是:
如果是一年的最后一天,则直接year++ month=1 day=1
其他情况则:
根据月份和天数计算出这是本年的第几天,然后加一
然后根据天数计算日期。算是之前两种方法的合并。但是比较好理解。
#include <bits/stdc++.h>
using namespace std;
#define N 100
class Date
{
private:
int year=0;
int month=0;
int day=0;
public:
void addDate();
Date(int a, int b, int c);
Date();
};
Date::Date(int a, int b, int c)
{
year = a;
month = b;
day = c;
}
Date::Date()
{
int year=0;
int month=0;
int day=0;
}
void Date::addDate()
{
if(month==12 && day==31)
{
year = year+1;
month = 1;
day = 1;
}
else
{
//由于是没有闰年测试,则二月为28
int dayarr[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int sum=0; //月中的日期累计
for(int i=1;i<=month-1;i++)
{
sum+=dayarr[i];
}
sum = sum+day+1;//实现加一
// 根据天数反向求日期
int sum_monthday = 0; //累计天数
int month_real = 0;//对应的月份
for(int i=1;i<=12;i++)
{
sum_monthday+=dayarr[i];
if(sum_monthday>=sum) //当累计天数大于实际天数 跳出
{
month_real = i;
break;
}
}
month = month_real;
//用sum减去当月之前的所有月份天数==当月的天数
//当月之前的所有天数=累计天数-本月天数
day = sum-(sum_monthday-dayarr[month]);
}
printf("%d-%02d-%02d\n", year, month, day);
}
int main()
{
int n = 0;
scanf("%d", &n);
Date D[N];
for(int i=0; i<n; i++)
{
int a=0,b=0,c=0;
scanf("%d %d %d", &a, &b, &c);
D[i]=Date(a,b,c);
}
for(int i=0; i<n; i++)
{
D[i].addDate();
}
return 0;
}