题解 | 日期累加

日期累加

https://www.nowcoder.com/practice/eebb2983b7bf40408a1360efb33f9e5d

#include <stdio.h>
//难点在于:1 闰年判断(4,100x;400) 2 年月日进制转换 3 改变后重新判断闰年和相应计算
int n[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int r[13] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};//闰年

int main() {
    int m;
    scanf("%d", &m);

    for (int case_num = 0; case_num < m; case_num++) { // 修复变量名冲突
        int y, mo, d, b,t=0;
        scanf("%d%d%d%d", &y, &mo, &d, &b);
        b += d;

        if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0) { // 闰年
            int current_month = mo; // 引入新变量表示当前月份
            while (b > 0) {
                if (current_month > 12) {//年变
                    current_month = 1;
                    y++;
                    t=1;
                }
                int days_in_month = r[current_month]; // 使用闰年数组
                if(t)//注意年份改变后,判断是否为闰年
                {
                    if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
                        days_in_month = r[current_month];
                       else  days_in_month = n[current_month];
                }
                if (b <= days_in_month) {
                    d = b;
                    mo = current_month;
                    printf("%04d-%02d-%02d\n", y, mo, d);
                    break;
                } else {
                    b -= days_in_month;
                    current_month++;
                }
            }
        } else { // 平年
            int current_month = mo;
            while (b > 0) {
                if (current_month > 12) {
                    current_month = 1;
                    y++;
                    t=1;
                }
                int days_in_month = n[current_month]; // 使用平年数组
                if(t)
                {
                    if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
                        days_in_month = r[current_month];
                       else  days_in_month = n[current_month];
                }
                if (b <= days_in_month) {
                    d = b;
                    mo = current_month;
                    printf("%04d-%02d-%02d\n", y, mo, d);
                    break;
                } else {
                    b -= days_in_month;
                    current_month++;
                }
            }
        }
    }

    return 0;
}

全部评论

相关推荐

04-13 18:10
门头沟学院 Java
想熬夜的小飞象在秋招:被腾讯挂了后爸妈以为我失联了
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务