酷代码 AI
菜单
服务商

日期计算神器:实现公元 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]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]