C语言实现日期天数计算

完整代码(C语言)

c 复制代码
#include <stdio.h>

int main() {
    int year, month, day;
    int days = 0;  // 累计天数

    // 输入年月日
    printf("请输入日期(年 月 日):");
    scanf("%d %d %d", &year, &month, &day);

    // switch 累加前面月份的总天数
    switch (month - 1) {
        case 11: days += 30;  // 11月
        case 10: days += 31;  // 10月
        case  9: days += 30;  // 9月
        case  8: days += 31;  // 8月
        case  7: days += 31;  // 7月
        case  6: days += 30;  // 6月
        case  5: days += 31;  // 5月
        case  4: days += 30;  // 4月
        case  3: days += 31;  // 3月
        case  2: days += 28;  // 2月(默认28天)
        case  1: days += 31;  // 1月
        case  0: days += day; // 加上当月的天数
    }

    // 判断闰年:2月多加1天
    if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
        if (month > 2) {
            days++;
        }
    }

    printf("这是 %d 年的第 %d 天\n", year, days);
    return 0;
}

核心原理

  1. switch 没有 break

    month-1 开始一路往下执行 ,把前面所有月份的天数全部累加

  2. 天数规则

    • 1、3、5、7、8、10、12月:31天
    • 4、6、9、11月:30天
    • 2月:平年28天,闰年29天
  3. 闰年判断

    满足:

    • 能被4整除但不能被100整除
    • 能被400整除
      如果月份大于2,总天数+1。

运行示例

输入:

复制代码
2025 3 15

输出:

复制代码
这是 2025 年的第 74 天
相关推荐
xh didida2 小时前
C++ -- string
开发语言·c++·stl·sring
lly2024062 小时前
Bootstrap 折叠组件详解
开发语言
无限进步_2 小时前
【C++&string】大数相乘算法详解:从字符串加法到乘法实现
java·开发语言·c++·git·算法·github·visual studio
苏纪云2 小时前
蓝桥杯考前突击
c++·算法·蓝桥杯
W23035765732 小时前
经典算法详解:最长公共子序列 (LCS) —— 从暴力递归到动态规划完整实现
算法·动态规划·最长子序列
pzx_0013 小时前
【优化器】 随机梯度下降 SGD 详解
人工智能·python·算法
‎ദ്ദിᵔ.˛.ᵔ₎3 小时前
模板template
开发语言·c++
大邳草民3 小时前
Python 中 global 与 nonlocal 的语义与机制
开发语言·笔记·python
charlie1145141913 小时前
通用GUI编程技术——图形渲染实战(二十九)——Direct2D架构与资源体系:GPU加速2D渲染入门
开发语言·c++·学习·架构·图形渲染·win32