debugcMinor
Functions that converts day of year to month and day and reverse with error checking
Viewed 0 times
erroryearconvertsreversewithcheckingthatmonthandfunctions
Problem
There is no error checking in
Here is the solution:
In the
In the
This exercise can be found in K&R2 at page 126.
day_of_year or month_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 = 1) && (day = 1 && yearday = 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.
Solution
-
Incorrect
-
-
-
Leap year calculation
-
Suggest
Incorrect
yearday limit// if((leap == 1 ... || (leap == 0 && (yearday >= 1 && yearday = 1 && yearday <= 365))) {
// 365-
month_day() and day_of_year() should use consistent types for month. Suggest int for both.// int day_of_year(unsigned int year, unsigned int month, int day) {
// void month_day(unsigned int year, unsigned int yearday, int *pmonth, int *pday) {
int day_of_year(unsigned int year, int month, int day) {-
month_day() and day_of_year() should use consistent types for yearday. Suggest int for both.// int day_of_year(unsigned int year, unsigned int month, int day) {
// void month_day(unsigned int year, unsigned int yearday, int *pmonth, int *pday) {
int day_of_year(unsigned int year, int month, int day) {
void month_day(unsigned int year, int yearday, int *pmonth, int *pday) {-
Leap year calculation
leap = ((year... is good back to 1583. For years 4 to 1582 it is leap = (year % 4 == 0); 1582 has other complications. Before 4 has complications.-
Suggest
month_day() return int to indicate success or failure.Code Snippets
// if((leap == 1 ... || (leap == 0 && (yearday >= 1 && yearday <= 366))) {
if((leap == 1 ... || (leap == 0 && (yearday >= 1 && yearday <= 365))) {
// 365// int day_of_year(unsigned int year, unsigned int month, int day) {
// void month_day(unsigned int year, unsigned int yearday, int *pmonth, int *pday) {
int day_of_year(unsigned int year, int month, int day) {// int day_of_year(unsigned int year, unsigned int month, int day) {
// void month_day(unsigned int year, unsigned int yearday, int *pmonth, int *pday) {
int day_of_year(unsigned int year, int month, int day) {
void month_day(unsigned int year, int yearday, int *pmonth, int *pday) {Context
StackExchange Code Review Q#41343, answer score: 4
Revisions (0)
No revisions yet.