日期计算神器:实现公元 1 年 1 月 1 日与指定日期的天数互算
```c #include <stdio.h> #include <stdlib.h> struct DateG { int yy, mm, dd; }; // 判断是否为闰年 char leapYear(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); } // 每个月的天数 int monthDays[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // 计算自公元1年1月1日到指定的日期共经历了多少天 int Days(struct DateG x) { int days = 0; // 计算之前年份的天数 for (int i = 1; i < x.yy; i++) { days += 365; if (leapYear(i)) days++; } // 计算当前年份到当前月份之前的天数 for (int i = 1; i < x.mm; i++) { days += monthDays[i]; if (i == 2 && leapYear(x.yy)) days++; } // 加上当前月份的天数 days += x.dd; return days; } // 由自公元1年1月1日历经指定的天数后的日期 struct DateG days2Date(int x) { struct DateG date = {1, 1, 1}; // 先减去年份的天数 while (1) { int yearDays = 365; if (leapYear(date.yy)) yearDays++; if (x > yearDays) { x -= yearDays; date.yy++; } else { break; } } // 再减去月份的天数 while (1) { int curMonthDays = monthDays[date.mm]; if (date.mm == 2 && leapYear(date.yy)) curMonthDays++; if (x > curMonthDays) { x -= curMonthDays; date.mm++; } else { break; } } // 剩余的天数就是日期 date.dd = x; return date; } // 以下为测试程序提供的测试用函数,这里简单实现 struct DateG _DateG(char *st) { struct DateG d; sscanf(st, "%d-%d-%d", &d.yy, &d.mm, &d.dd); return d; } struct DateG Add(struct DateG x, int y) { int totalDays = Days(x) + y; return days2Date(totalDays); } char* Date2string(struct DateG x) { static char str[12]; sprintf(str, "%04d-%02d-%02d", x.yy, x.mm, x.dd); return str; } ``` ######[AI问答 | 723点数解答 | 2025-12-11 13:16:19]
- Python 实现球类:精准计算半径、表面积与体积,附输入验证与异常处理!(阿里通义 | 261点数解答 | 2024-11-28 21:19:39)345
- C++ 代码:从儒略日精准计算公历日期及复杂度分析(字节豆包 | 1156点数解答 | 2026-02-08 19:36:11)33
- 51 单片机:定时器 0 实现 8 个 LED 循环点亮,附代码及优化建议(字节豆包 | 1193点数解答 | 2024-12-27 15:10:29)313
- C++ 代码实现自定义运算 x@y = x² + y² - xy 及 x@(x+y) 计算(DeepSeek | 215点数解答 | 2025-12-13 15:08:14)70
- C++ 实现根据输入正整数奇偶性计算偶数和或约数和(字节豆包 | 838点数解答 | 2026-02-28 20:23:59)26
- Excel 日期格式显示####?这些解决办法快收好!( | 327点数解答 | 2023-12-29 09:53:45)280
- Java实现日程管理系统:添加、修改、查询与提醒一应俱全,数据本地txt保存!(GPT | 5818点数解答 | 2024-06-03 20:02:47)344
- 用Python处理商品销售数据:替换类别、合并类目并输出前5行(百度文心 | 486点数解答 | 2024-08-23 09:14:21)311
- 双11前小明巧用数据:计算机械键盘与游戏鼠标最近购买均价!(字节豆包 | 32点数解答 | 2024-10-17 20:43:03)211
- 云南 8 日摄影行程表 HTML 代码优化与逻辑注意点揭秘(字节豆包 | 217点数解答 | 2025-03-09 13:19:03)264
- 新员工7月业绩冲刺计划书:15天填补28000元缺口,附Word转换指南!(DeepSeek | 233点数解答 | 2025-07-16 18:48:05)110
- 新员工业绩达标计划书:完善方案待店长审批,多维度优化冲刺7月目标!(字节豆包 | 500点数解答 | 2025-07-16 18:50:16)98