酷代码 AI
菜单

6-1 日期几何 分数 10 作者 Happyer 单位 湖北文理学院 关于日期的结构定义如下: struct DateG{ int yy,mm,dd;}; 编写两个函数,一个计算自公元1年1月1日到指定的日期共经历了多少天。另一个是前一个函数的逆函数:由自公元1年1月1日历经指定的天数后的日期(返回年月日构成的日期)。 函数接口定义: struct DateG days2Date(int x);{//from:{1,1,1} + 100-->{1,4,11} int Days(DateG x);// {2,,4,11} return 465 from{1,1,1} 裁判测试程序样例: struct DateG{ int yy,mm,dd; }; char leapYear(int year);//闰年否 struct DateG _DateG(char *st);{//"1919-9-9"-->{1919,9,9} struct DateG Add(struct DateG x,int y);//{1919,9,9}+50-->{1919,10,29}

```c #include <stdio.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 year = 1; year < x.yy; year++) { days += 365 + leapYear(year); } // 计算当前年份到当前月份之前的总天数 for (int month = 1; month < x.mm; month++) { days += monthDays[month]; if (month == 2 && leapYear(x.yy)) { days++; } } // 加上当前月份的天数 days += x.dd; return days; } // 由自公元1年1月1日历经指定的天数后的日期 struct DateG days2Date(int x) { struct DateG date = {1, 1, 1}; int year = 1; // 先减去之前年份的天数 while (1) { int daysInYear = 365 + leapYear(year); if (x > daysInYear) { x -= daysInYear; year++; } else { break; } } date.yy = year; // 减去当前年份到当前月份之前的天数 int month = 1; while (1) { int daysInMonth = monthDays[month]; if (month == 2 && leapYear(year)) { daysInMonth++; } if (x > daysInMonth) { x -= daysInMonth; month++; } else { break; } } date.mm = month; date.dd = x; return date; } // 测试用函数,这里仅为满足代码结构,不做具体实现 struct DateG _DateG(char *st) { struct DateG date; sscanf(st, "%d-%d-%d", &date.yy, &date.mm, &date.dd); return date; } struct DateG Add(struct DateG x, int y) { int days = Days(x) + y; return days2Date(days); } char* Date2string(struct DateG x) { static char str[12]; sprintf(str, "%04d-%02d-%02d", x.yy, x.mm, x.dd); return str; } 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; } ``` 代码解释: 1. `leapYear` 函数:用于判断某一年是否为闰年。如果是闰年返回 `1`,否则返回 `0`。 2. `Days` 函数:计算从公元1年1月1日到指定日期的总天数。先计算之前年份的总天数,再计算当前年份到当前月份之前的总天数,最后加上当前月份的天数。 3. `days2Date` 函数:根据从公元1年1月1日开始的总天数计算对应的日期。先减去之前年份的天数,确定年份;再减去当前年份到当前月份之前的天数,确定月份;最后剩余的天数就是当前月份的日期。 4. `_DateG` 函数:将输入的字符串转换为 `struct DateG` 类型的日期。 5. `Add` 函数:在指定日期上加上或减去指定的天数,通过调用 `Days` 和 `days2Date` 函数实现。 6. `Date2string` 函数:将 `struct DateG` 类型的日期转换为字符串。 7. `main` 函数:读取输入的日期,计算60年后的日期、退休前倒计时1000天的日期以及武汉抗疫封城时的年龄,并输出结果。 [2025-12-12 20:17:01 | AI问答 | 1188点数解答]

服务商
相关提问
发财导航,免费问AI
实用工具查看更多