From b782b3f9b677d2fcfdbf79a30b3fd4e8a0002aec Mon Sep 17 00:00:00 2001 From: Martin Ashby Date: Sat, 11 Feb 2023 17:35:26 +0000 Subject: Exercise 5.10 --- ex5-8.c | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 ex5-8.c (limited to 'ex5-8.c') diff --git a/ex5-8.c b/ex5-8.c new file mode 100644 index 0000000..1f74a19 --- /dev/null +++ b/ex5-8.c @@ -0,0 +1,58 @@ +#include +#define NDEBUG +#include + +static char daytab[2][13] = { + {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, + {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} +}; + +/* day_of_year: set day of year from month & day */ +int day_of_year(int year, int month, int day) +{ + assert(month >= 1); + assert(month <= 12); + + int i, leap; + + leap = (year%4 == 0 && year%100 != 0) || year%400 == 0; + + assert(day >= 1); + assert(day <= *(*(daytab+leap) + month)); + + for (i = 1; i < month; i++) + day += *(*(daytab+leap) + i); + return day; +} + +/* month_day: set month, day from day of year */ +void month_day(int year, int yearday, int *pmonth, int *pday) +{ + int i, leap; + + leap = (year%4 == 0 && year%100 != 0) || year%400 == 0; + + assert(yearday >= 1); + assert(yearday <= (leap ? 366 : 365)); + + for (i = 1; yearday > *(*(daytab+leap)+i); i++) + yearday -= *(*(daytab+leap)+i); + *pmonth = i; + *pday = yearday; +} + +int main(void) { + // Add error checking eh + int doy, dom, month; + doy = day_of_year(2022, 2, 8); + month_day(2022, doy, &month, &dom); + + printf("2022-02-08 doy=%d month=%d dom=%d\n", doy, month, dom); + + doy = day_of_year(2022, 0, 8); + doy = day_of_year(2022, 13, 8); + doy = day_of_year(2022, 12, 0); + doy = day_of_year(2022, 12, 32); + doy = day_of_year(2022, 2, 29); + doy = day_of_year(2024, 2, 29); // This one is ok +} \ No newline at end of file -- cgit v1.2.3-ZIG