diff options
Diffstat (limited to 'ex5-8.c')
-rw-r--r-- | ex5-8.c | 58 |
1 files changed, 58 insertions, 0 deletions
@@ -0,0 +1,58 @@ +#include <stdio.h> +#define NDEBUG +#include <assert.h> + +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 |