I am new to programming and have been having a problem with my program. It is supposed to convert a date into day of the year (1\31 is the 31st day, 2\1 is the 32nd). When inputting inputting a date in Jan or Feb the program works, but the other monthes give an output like "It is the -858993398th day of the year." I'm not sure why. This is the code:
#include <iostream.h>
int main()
{
int m, d, y, i = 0, leap, date, n, r;
bool valid;
char slash;
cout << "\nEnter date in MM/DD/YYYY form\n";
cin >> m >> slash >> d >> slash >> y;
if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12)
{
if (d < 32)
{valid = true;
} }
elseif(m == 4 || m == 6 || m == 9 || m == 11)
{
if (d < 31)
{valid = true;
} }
elseif(m == 2)
{if (d <= 28)
{valid = true;
leap = 0;
}
elseif (d == 29)
{for(i;i <= y; i += 4)
{if(i == y)
{valid = true;}
else
{valid = false;}
} } }
else
{valid = false;}
if (valid == false)
{
cout << "\nInvalid Entry\n";
return 0;
}
switch(m)
{
case 1:
date = d;
break;
case 2:
date = 31 + d + leap;
break;
case 3:
date = 59 + d + leap;
break;
case 4:
date = 90 + d + leap;
break;
case 5:
date = 120 + d + leap;
break;
case 6:
date = 151 + d + leap;
break;
case 7:
date = 181 + d + leap;
break;
case 8:
date = 212 + d + leap;
break;
case 9:
date = 243 + d + leap;
break;
case 10:
date = 273 + d + leap;
break;
case 11:
date = 304 + d + leap;
break;
case 12:
date = 334 + d + leap;
break;
}
cout << "\nThe date you entered was " << m << "/" << d << "/" << y;
cout << "\nIt is the " << date;
if(date != 11 && date != 12 && date != 13)
{n = date % 10;
if(n > 10 && n != 11 && n != 12 && n != 13)
{r = n % 10;}
else{
r = n;}
}
else
{cout << "th day of the year.\n";
}
switch(r)
{
case 1:
cout << "st day of the year.\n";
break;
case 2:
cout << "nd day of the year.\n";
break;
case 3:
cout << "rd day of the year.\n";
break;
default:
cout << "th day of the year.\n";
}
return 0;
}
this happens because in january you don't use 'leap'
if february you will probably get the days passed in february, because leap=0 when d<=28.
if you use 29 february 2000 you will probably also get wrong results because leap doen't get a value assigned as well.
for the rest of the monht's leap remains unnasigned, so whatever value is in memory on the location of leap is taken as an integer value for your calculations.
With proper assignment of leap your program will probably work fine