The code has the same end result as the last one.. It must tell the user how
many days it has been since their birthday. Now it does give a result but
its normally off by a bit.. I have figured out which bit of the code is
causing this error, but, can't figure out exactly what is wrong with it! :(
The bit of code that is incorrect I have highlighted below.
#include <stdio.h>
static int YearDb [2][13] = { //A database of the number of days in each
month in a normal and a leap year.
{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}
};
int leapyr(int year) { //Works out whether a given year is a leap year or
not.
if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
return 1;
} else {
return 0;
}
}
int main(void) {
int day, mnth, yr;
int tday, tmnth, tyr;
int i = 0;
int dayCount = 0;
//Prompt the user for birthdate.
printf("Please enter your birthday [DD/MM/YYYY]: ");
//Read in the birthday.
scanf("%2d/%2d/%4d", &day, &mnth, &yr);
printf("\n\n");
//Prompt the user for today's date.
printf("Please enter today's date [DD/MM/YYYY]: ");
//Read in the date.
scanf("%2d/%2d/%4d", &tday, &tmnth, &tyr);
printf("\n\n");
dayCount = tday; //Add this months days
// THIS BIT IS THE CODE THAT DOES NOT FUNCTION AS EXPECTED >>
// This adds all this years days up to now.
if(leapyr(tyr) != 1) {
for(i = (tmnth - 1); i > 0; i--) {
dayCount += YearDb[1][i];
}
} else {
for(i = (tmnth - 1); i > 0; i--) {
dayCount += YearDb[2][i];
}
}
// THIS BIT IS THE CODE THAT DOES NOT FUNCTION AS EXPECTED <<
// Adds all the years days from last year till the year after their
birthdate.
for(i = (tyr - 1); i > yr; i--) {
if(leapyr(i) != 1) {
dayCount += 365;
} else {
dayCount += 366;
}
}
// Adds days till the end of the month from birthday.
if(leapyr(yr) != 1) {
dayCount += (YearDb[1][mnth] - day);
} else {
dayCount += (YearDb[2][mnth] - day);
}
// Adds the remaining months of the birthyear.
if(leapyr(yr) != 1) {
for(i = (mnth + 1); i >= 12; i++) {
dayCount += YearDb[1][i];
}
} else {
for(i = (mnth + 1); i >= 12; i++) {
dayCount += YearDb[2][i];
}
}
printf("You have been alive for %d days!", dayCount);
getchar();
getchar();
return 0;
}