Number to Date forumla help

I need help creating a formula that will return a number 1-12 when the user enters 1-365. The point is to figure out what month a user entered day with fall in. Ex: User enters 1 - January, 32 - Feb, 365 - Dec, etc.

I could go through and code if num >= 1 && num =< 31 then cout << "Jan", etc for every month, but I feel like a formula might be yield a quicker result.

Any help is greatly appreciated.
There really is no formula for this because of the randomness of days per month. If every month had exactly 30 days then you could do this:

1
2
3
4
5
6
7
8
#include <math.h> //so that you can use the ceil function
int day;
float month;

cout<< "Enter day:";
cin >> day;

month = ceil( (float)day / 30); 
Last edited on
If you don't want to use a lot of if statements you could store the number of days for each month in an array and use that to calculate the correct month.
I like the idea Peter. But I couldn't get it to work so far. Why isn't the int result adding the total of each array subscript as it steps through?

int main()
{
int NumberOfDays;
const int NUMBER_OF_MONTHS = 12;
int result = 0;
int monthDays[NUMBER_OF_MONTHS] = {31, 28, 31,30, 31, 30, 31, 31, 30, 31, 30, 31};

cout << "Enter a number between 1-365 and I will tell you " << endl;
cout << "the month: ";
cin >> NumberOfDays;
cout << endl;

for (int count = 0; count < NUMBER_OF_MONTHS; count++)
{
if (NumberOfDays > monthDays[count])
result = NumberOfDays - monthDays[count];
else if (NumberOfDays < monthDays[count])
break;
}

cout << result;
system("PAUSE");
return(0);
}
Nevermind, I just got it. Thanks for the idea!!
Topic archived. No new replies allowed.