给定一年中的年月日,计算该日期加上若干天后是什么日期?
关于输入:
第一行输入样例个数m, 在下面的m行中,每行分别输入4个整数,表示年月日和增加的天数
关于输出:
输出m行,每行按照“04d-02d-02d”的格式输出,例如“2001-01-01”
分析:
可以采取先计算出该日期在本年中是第几天;加上经过的天数并判断是否有“跨年”情况的出现,若有则更新年份;最后将总天数再转化为日期的形式。
注:关于指定格式的输出,如
- %2d 表示输出宽度为2的整数,如果超过2位则按照实际情况输出,否则右对齐输出;
- %02d 表示输出场宽为2的整数,如果超过2位则按照实际情况输出,否则补0至2位;
- %5.2f 表示输出场宽为5的浮点数,不够5位则右对齐输出,其中小数点后保留2位。
# include <cstdio>
# include <iostream>
using namespace std;
// if this year a "RUN" year
int isRunYear(int year){
if ((year%4==0 && year%100!=0) || (year%400==0)){
return 1;
}
else{
return 0;
}
}
// how many days in every month
int monthTable[2][13] = {
{
0,31,28,31,30,31,30,31,31,30,31,30,31},
{
0,31,29,31,30,31,30,31,31,30,31,30,31}};
int dayInYear[2] = {
355,356};
int main(){
int casenumber;
cin >> casenumber;
while(casenumber--){
int year, month, day, moreday;
int total = 0;
cin >> year >> month >> day >> moreday;
int row = isRunYear(year);
// first compute the total day now
for (int i=0; i < month; ++i){
total += monthTable[row][i];
}
total += day + moreday;
// plus more days and judge if the years increased
while(total > dayInYear[isRunYear(year)]){
total -= dayInYear[isRunYear(year)];
year += 1;
}
// renew the data
row = isRunYear(year);
month = 0;
for ( ; total>monthTable[row][month]; ++month){
total -= monthTable[row][month];
}
day = total;
// output
printf("%04d-%02d-%02d", year, month, day);
}
return 0;
}