You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C语言计算出生年年初至出生日期的间隔天数

C语言计算年初到出生日期总天数实现方案

前置修正:原有闰年判断逻辑问题

你现有代码中2月天数的判断规则存在遗漏,未覆盖世纪闰年场景(即整百年份能被400整除的情况,例如2000年是闰年,1900年不是),后续实现会先修正该逻辑。

前序月份总天数累加实现思路

最简便的实现方式是通过预置平年各月份天数的数组,结合闰年判断动态调整2月天数,再遍历累加出生月份之前的所有月份天数即可,完整实现代码如下:

#include <stdio.h>

int main() {
    int myd, mym, myy;
    printf("Enter your day of birth:");
    scanf("%d", &myd);
    printf("Enter your month of birth:");
    scanf("%d", &mym);
    printf("Enter your year of birth:");
    scanf("%d", &myy);

    // 预置平年各月天数,下标1对应1月,下标12对应12月
    int month_days[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
    int total_days = 0;
    int is_leap = 0;

    // 修正后的闰年判断规则
    if((myy % 4 == 0 && myy % 100 != 0) || (myy % 400 == 0)) {
        is_leap = 1;
        month_days[2] = 29; // 闰年2月调整为29天
    }

    // 累加前序月份总天数
    for(int i = 1; i < mym; i++) {
        total_days += month_days[i];
    }
    // 加上出生日期的日数
    total_days += myd;

    printf("从出生年年初到生日的总天数为:%d\n", total_days);

    // 可选补充:输入合法性校验逻辑
    if(mym <1 || mym >12 || myd <1 || myd > month_days[mym]) {
        printf("输入的出生日期不合法,请检查\n");
        return 1;
    }

    return 0;
}

代码逻辑说明

  • 用长度为13的数组存储各月天数,避免月份和数组下标的偏移转换,代码可读性更高
  • 闰年判断逻辑覆盖所有场景:普通闰年(能被4整除但不能被100整除)、世纪闰年(能被400整除)
  • 循环遍历1到出生月份前一个月,累加所有月份天数,最后加上出生日期的日数,即可得到最终结果

内容的提问来源于stack exchange,提问作者Eaza Kae

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 02:06:08