Hi everyone!
I'm trying to learn C from my dad's old college textbooks, and I'm doing some of the problems he had to do. This problem is meant to calculate the number of days between two dates given by the user. I made a function to account for leap years, and to input the data. My program is running, but is coming up with numbers that are just a few days off. I already wrote this program in Pascal, and it works, but I'm trying to practice it in C.
Here's the source code.
/*This program counts the days between two dates input by the user*/
#include <stdio.h>
int yr1; /*global variables because all these need to be visible by multiple functions*/
int yr2; /*I don't know how to use pointers to return more than 1 variable from a function*/
int m1;
int m2;
int d1;
int d2;
int leap;
main()
{
int numdays [13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; /*13 members*/
int totaldays; /*so that 1 would match up with January, fixing notation problems*/
int year;
int month;
int day;
inputdata();
for (year = (yr1 + 1); year < yr2; year ++) /*processes complete years*/
{
leapyr(year);
if (leap == 1)
totaldays += 366;
else totaldays += 365;
}
year = yr1;
for(month = m1 + 1; month <= 12; month++) /*processes incomplete year 1*/
{
leapyr (year);
if (leap == 1)
numdays[2] = 29;
else numdays[2] = 28;
totaldays = totaldays + numdays[month];
}
month = m1;
for(day = d1; day <= numdays [month]; day++) /*processes incomplete month 1*/
{
leapyr (year);
if (leap == 1)
numdays[2] = 29;
totaldays += 1;
}
year = yr2;
for(month = m2 - 1; month >= 1; month--) /*processes incomplete year 2*/
{
leapyr (year);
if (leap == 1)
numdays[2] = 29;
totaldays += numdays[month];
}
month = m2;
for(day = d2; day > 1; --day) /*processes incomplete month 2*/
{
totaldays += 1; /*no need for leapyr function here- don't need to know month max*/
}
printf("Total number of days between two given dates is: %d days", totaldays);
getch();
}
int inputdata() /*function works as planned- already tested*/
{
printf("This program calculates the number of days between two given dates\n");
printf("Enter beginning date in form month/day/year: ");
scanf( "%d/%d/%d", &m1, &d1, &yr1);
printf("Enter ending date in form month/day/year: ");
scanf("%d/%d/%d", &m2, &d2, &yr2);
}
int leapyr (year)
{
int leap = 0;
if (year % 4 == 0)
leap = 1;
else
if (year % 100 == 0)
leap = 0;
else
if (year % 400 == 0)
leap = 1;
printf("leap is: %d\n", leap);
return leap;
}
Thanks for the help!