-
Notifications
You must be signed in to change notification settings - Fork 0
/
day.c
55 lines (39 loc) · 1.21 KB
/
day.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include "stdio.h"
int day_of_year(int year, char month, int day);
char monthday(int year, int day, char *m, char *d);
int main(void) {
char m, d;
printf("day of year: %d\n",
day_of_year(2020, 9, 25));
monthday(2020, day_of_year(2020, 9, 25), &m, &d);
printf("month: %d, day: %d\n", m, d);
return 0;
}
static char daytab[][12] = {
{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
int day_of_year(int year, char month, int day) {
char leap, i;
leap = year%4 == 0 && year%100 != 0 || year%400 == 0;
if (month < 1 || month > 12)
return 0; // wrong month
// Exercise 5-9. Rewrite the routines day_of_year and month_day with
// pointers instead of indexing.
if (day > *(daytab + leap * 12 + month - 1))
return -1; // wrong day
for (i = 0; i < month - 1; i++)
day += daytab[leap][i];
return day;
}
char monthday(int year, int day, char *m, char *d) {
char leap, i;
leap = year%4 == 0 && year%100 != 0 || year%400 == 0;
if (day > (leap ? 366 : 365))
return 0; // wrong day
for (i = 0; day > daytab[leap][i]; i++)
day -= daytab[leap][i];
*m = i + 1;
*d = day;
return 1; // fin
}