Given a year, month, and day of the year, calculate what date is that date plus the number of days?
About input:
the first line enters the number of samples m, and in the following m lines, each line enters 4 integers, representing the year, month, day and the number of days added
About output:
output m lines, each line is output in the format of "04d-02d-02d", such as "2001-01-01"
Analysis:
You can first calculate the date in the current year; add the number of days passed and judge whether there is a "cross-year" situation, and update the year if there is; finally convert the total number of days into the date form.
Note: Regarding the output of the specified format, such as
- %2d means to output an integer with a width of 2. If it exceeds 2 digits, it will be output according to the actual situation, otherwise it will be right-aligned and output;
- %02d represents an integer whose output field width is 2, if it exceeds 2 digits, it will be output according to the actual situation, otherwise it will be filled with 0 to 2 digits;
- %5.2f means to output a floating-point number with a field width of 5. If there are less than 5 digits, the output will be right-aligned, and 2 digits will be reserved after the decimal point.
# 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;
}