There is no error checking in
day_of_year
ormonth_day
. remedy this defect.
Here is the solution:
int day_of_year(unsigned int year, unsigned int month, int day) {
int leap, i;
leap = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
if(((month >= 1) && (month <= 12)) && ((day >= 1) && (day <= daytab[leap][month]))) {
for(i = 1; i < month; i++) {
day += daytab[leap][i];
}
return day;
}
return -1;
}
void month_day(unsigned int year, unsigned int yearday, int *pmonth, int *pday) {
int leap, i;
leap = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
if((leap == 1 && (yearday >= 1 && yearday <= 366)) || (leap == 0 && (yearday >= 1 && yearday <= 366))) {
for(i = 1; yearday > daytab[leap][i]; i++) {
yearday -= daytab[leap][i];
}
*pday = yearday;
*pmonth = i;
}
else {
printf("error: the yearday is invalid");
}
}
In the day_of_year
's case I have to check if the yearday
is a valide one. 1 <= yearday <= (365 || 366)
. I changed the parameters type to unsigned, because a day can't be negative nor a year.
In the month_day
's case I check if the month
is a valid one, it should be 1 <= month <= 12
. After this, I check if the day
belongs to a valid interval.
This exercise can be found in K&R2 at page 126.