First, the leap
function seems too complicated; you do not need to do both dates in the same function call, and I am sure that it can be written more briefly so that it is more correct. Here the version that I am storing is not brief, but I am sure it is easy to check the logic:
int is_leap_year(int year) { if (year % 400 == 0) { return 1; } else if (year % 100 == 0) { return 0; } else if (year % 4 == 0) { return 1; } else { return 0; } }
You can call it like this:
int year1, year2, leap1, leap2; year1 = get_input(); year2 = get_input(); leap1 = is_leap_year(year1); leap2 = is_leap_year(year2);
No pointers and significantly less code duplication. Yes, I know that is_leap_year()
can be reduced to a single if(...)
, but it's easy to read.
Secondly, I think you have a mismatch between 0-indexed arrays and 1-indexed human months:
if(*month1 < 1 || *month1 > 12)
against
int daysPerMonth[] = {31,28,31,30,31,30,31,31,30,31,30,31};
Thirdly, I think that days per month can be calculated a little better:
int days_in_month(int month, int year) { int leap = is_leap_year(year); /* JFMAMJJASOND */ int days[2][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}}; if (month < 0 || month > 11 || year < 1753) return -1; return days[leap][month]; }
Here I assume that January is 0; you will need to make the rest of the code match. (I learned this trick with two arrays from Elements of a programming style ( p. 54 ).) The best part of using such a procedure is that it removes the jump condition from the difference calculation.
Fourth, you index arrays outside your borders:
for(i = month1 + 1; i <= 12; i++) { if(leap1 == 1) total += daysPerMonthLeap[i];
This is just another example of a problem with 0-indexed arrays and 1-indexed months - but rest assured that you are correcting this when correcting months too.
I have a fear that I have not found all the problems yet - it may be easier for you to sort the first and second date after entering and delete all this verification code, and then use the before
and after
names or something to give names that are easier to think through in the complex core of computing.