日期计算秘籍:从公元 1 年 1 月 1 日起的天数与日期转换全解析
```c #include <stdio.h> #include <string.h> struct DateG { int yy, mm, dd; }; // 判断是否为闰年 char leapYear(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); } // 计算每个月的天数 int daysInMonth(int year, int month) { int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; if (month == 2 && leapYear(year)) { return 29; } return days[month - 1]; } // 计算自公元1年1月1日到指定的日期共经历了多少天 int Days(struct DateG x) { int totalDays = 0; // 计算之前年份的总天数 for (int year = 1; year < x.yy; year++) { totalDays += leapYear(year) ? 366 : 365; } // 计算当前年份当前月之前月份的总天数 for (int month = 1; month < x.mm; month++) { totalDays += daysInMonth(x.yy, month); } // 加上当前月的天数 totalDays += x.dd; return totalDays; } // 由自公元1年1月1日历经指定的天数后的日期 struct DateG days2Date(int x) { struct DateG date = {1, 1, 1}; while (x > 0) { int daysInThisYear = leapYear(date.yy) ? 366 : 365; if (x >= daysInThisYear) { x -= daysInThisYear; date.yy++; } else { for (int month = 1; month <= 12; month++) { int daysInThisMonth = daysInMonth(date.yy, month); if (x >= daysInThisMonth) { x -= daysInThisMonth; date.mm++; } else { date.dd = x; x = 0; break; } } } } return date; } // "1919-9-9" --> {1919,9,9} struct DateG _DateG(char *st) { struct DateG date; sscanf(st, "%d-%d-%d", &date.yy, &date.mm, &date.dd); return date; } // {1919,9,9}+50 --> {1919,10,29} struct DateG Add(struct DateG x, int y) { int totalDays = Days(x) + y; return days2Date(totalDays); } // {1919,9,9} --> "1919-09-09" char* Date2string(struct DateG x) { static char result[12]; sprintf(result, "%04d-%02d-%02d", x.yy, x.mm, x.dd); return result; } int main() { char st[12]; scanf("%s", st); struct DateG d1 = _DateG(st); struct DateG d2 = Add(d1, 60 * 365); printf("%s\n", Date2string(d2)); d2 = Add(d2, -1000); printf("%s\n", Date2string(d2)); d2 = _DateG("2020-1-23"); printf("%.2f\n", (Days(d2) - Days(d1)) / 365.0); return 0; } ``` ######[AI问答 | 951点数解答 | 2025-12-12 20:56:37]
- C++ 代码:从儒略日精准计算公历日期及复杂度分析(字节豆包 | 1156点数解答 | 2026-02-08 19:36:11)35
- Golang开发:解析JSON数据时数值默认类型及示例解析(百度文心 | 393点数解答 | 2023-11-09 18:13:06)284
- SQL Working Areas Sizing: Manual vs. Automatic Policy - A Comprehensive Analysis(阿里通义 | 530点数解答 | 2024-05-13 10:55:58)312
- C++ 代码实现自定义运算 x@y = x² + y² - xy 及 x@(x+y) 计算(DeepSeek | 215点数解答 | 2025-12-13 15:08:14)80
- C++ 实现根据输入正整数奇偶性计算偶数和或约数和(字节豆包 | 838点数解答 | 2026-02-28 20:23:59)32
- Excel 日期格式显示####?这些解决办法快收好!( | 327点数解答 | 2023-12-29 09:53:45)282
- Java实现日程管理系统:添加、修改、查询与提醒一应俱全,数据本地txt保存!(GPT | 5818点数解答 | 2024-06-03 20:02:47)346
- 用Python处理商品销售数据:替换类别、合并类目并输出前5行(百度文心 | 486点数解答 | 2024-08-23 09:14:21)317
- 双11前小明巧用数据:计算机械键盘与游戏鼠标最近购买均价!(字节豆包 | 32点数解答 | 2024-10-17 20:43:03)215
- 云南 8 日摄影行程表 HTML 代码优化与逻辑注意点揭秘(字节豆包 | 217点数解答 | 2025-03-09 13:19:03)268
- 新员工7月业绩冲刺计划书:15天填补28000元缺口,附Word转换指南!(DeepSeek | 233点数解答 | 2025-07-16 18:48:05)112
- 新员工业绩达标计划书:完善方案待店长审批,多维度优化冲刺7月目标!(字节豆包 | 500点数解答 | 2025-07-16 18:50:16)99