forked from jhpy1024/CProgrammingLanguageExercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exercise_5-9.c
70 lines (53 loc) · 1.63 KB
/
exercise_5-9.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <stdio.h>
/* Each sub-array has 13 elements as the first element is not used. This is so indices intuitively start at 1. */
static char days_per_month[][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 } /* Leap year. */
};
int is_leap_year(int year)
{
return (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0);
}
int day_of_year(int year, int month, int day)
{
int is_leap = is_leap_year(year);
if (day > days_per_month[is_leap][month])
{
printf("error: invalid day %d. there are %d days in month %d in the year %d\n", day, days_per_month[is_leap][month], month, year);
return -1;
}
char* first_month = &days_per_month[is_leap][1];
char* month_ptr;
for (month_ptr = first_month; month_ptr < first_month + month; ++month_ptr)
{
day += *month_ptr;
}
return day;
}
void month_day(int year, int day_of_the_year, int* month, int* day)
{
if (day_of_the_year > 365)
{
printf("error: invalid day of the year %d. there are 365 days in a year\n", day_of_the_year);
}
int is_leap = is_leap_year(year);
char* first_month = &days_per_month[is_leap][1];
char* month_ptr;
for (month_ptr = first_month; day_of_the_year > *month_ptr; ++month_ptr)
{
day_of_the_year -= *month_ptr;
}
*month = month_ptr - first_month;
*day = day_of_the_year;
}
int main()
{
int month;
int day;
int year = 2014;
int doy = 32;
month_day(year, doy, &month, &day);
printf("%d/365 (%d) -> %d-%d-%d\n", doy, year, year, month, day);
return 0;
}