Program that converts a month and a date to a day of the year.

I have to modify the code below to make it work, so when the user types in a month and a date, it converts it into a day of the year. Example; (mm,dd)= (2/1) = February 1, would be day 32 of the year. what would the code look like. Im stuck and i dont understand how you would do it.



# include < iostream >
# include < string >
using namespace std ;
// Summary :
// Checks the date given by month ’m’ and day ’d’ to make sure it is valid .
// If yes , the function returns true and the ’ dateAsString ’ parameter contains
// the date formatted as a string (e.g. , " January 1") , otherwise , the
// ’ dateAsString ’ parameter will contain " Invalid ".
bool checkDate ( int m , int d , string & dateAsString );
/*
Summary :
Retruns the day of year from month ’m ’, and day ’d ’. The function requires
that the input values are representative of a valid calendar date .
*/
int computeDayOfYear (int m , int d );
/**
* Summary :
* Outputs the ’ dateAsString ’ and corresponding day of year ’doy ’ to the screen .
* For example : " January 1 is day of year 1".
*/
void output ( const string & dateAsString , int doy );
int main ()
{
bool validDate = false ;
int month , day , doy ; // doy = day of year
string dateAsText ;
cout << " Welcome to the date converter program " << endl ;
while (! validDate )
{
cout << " Enter a number between 1 and 12 for the month : ";
cin >> month ;
cout << " Enter the day of the month : ";
cin >> day ;
validDate = checkDate ( month , day , dateAsText );
if (! validDate )
cout << " Invalid date , please try again " << endl ;
}
doy = comupteDayOfYear ( month , day );
output ( dateAsText , doy );
return 0;
}
Last edited on
If you ignore leap years, its a fixed computation.
make a lookup table of # of days in each month:
int dayz[] = {0,31 ,28 ,31 ,30 ,31 ,30 ,31 ,31 ,30 ,31 ,30 ,31 };
and then just add:
result = dayz[month-1]+days;
so 2,1
becomes
days[2-1] which is 31, + 1, is 32.
that zero makes it work for jan days:
1,10 gives 0+10 = 10.

Topic archived. No new replies allowed.