编辑代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 判断是否是闰年,是则返回1,否则返回0
int is_leap_year(int year) {
    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
        return 1;
    } else {
        return 0;
    }
}

// 返回某个月份的天数,考虑闰年的情况
int get_days_of_month(int year, int month) {
    int days = 0;
    switch (month) {
        case 1: case 3: case 5: case 7: case 8: case 10: case 12:
            days = 31;
            break;
        case 4: case 6: case 9: case 11:
            days = 30;
            break;
        case 2:
            if (is_leap_year(year)) {
                days = 29;
            } else {
                days = 28;
            }
            break;
        default:
            printf("Invalid month!\n");
            exit(1);
    }
    return days;
}

// 计算日期的函数,输入当前的年月日和需要推算的天数,输出推算后的年月日
static void calculate_date(char* current_date, int delta,char* upgrade_date) 
{
	int year = 0;
	int month = 0;
	int day = 0;
	char upg_date[64];
	sscanf(current_date, "%04d-%02d-%02d", &year, &month, &day);
    // 如果delta为正数,表示向后推算
    if (delta > 0) {
        while (delta > 0) {
            if (day == get_days_of_month(year, month)) {
                day = 1;
                if (month == 12) {
                    month = 1;
                    year++;
                } else {
                    month++;
                }
            } else {
                day++;
            }
            delta--;
        }
    } else if (delta < 0) {
        while (delta < 0) {
            if (day == 1) {
                if (month == 1) {
                    month = 12;
                    year--;
                } else {
                    month--;
                }
                day = get_days_of_month(year, month);
            } else {
                day--;
            }
            delta++;
        }
    }
    // 输出推算后的日期
	sprintf(upg_date, "%d-%d-%d", year,month,day);
	strcpy(upgrade_date,upg_date);
	printf("Next upgrade date is: %s\n",upgrade_date);
    //printf("The calculated date is %d-%d-%d\n", year, month, day);
}

// 主函数,从标准输入读取当前的年月日和需要推算的天数,调用计算日期的函数
int main() {
    int year, month, day, delta;
    char current_date[64];
    char upgrade_date[64];
    printf("Please enter the current date (year-month-day): ");
    scanf("%d-%d-%d", &year, &month, &day);
    sprintf(current_date,"%4d-%2d-%2d",year,month,day);
    printf("Please enter the number of days to calculate (positive for forward, negative for backward): ");
    scanf("%d", &delta);
    calculate_date(current_date, delta,upgrade_date);
    return 0;
}