酷代码 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> #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; } ``` [2025-12-11 13:16:19 | AI问答 | 723点数解答]

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