1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
#include <iostream>
using namespace std;
namespace mycalendar {
const int days_per_month[] = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
// is_leap_year()
// Returns whether the given argument represents a leap year.
//
bool is_leap_year( int year ) {
return ((year % 400) == 0)
|| ( ((year % 100) != 0)
&& ((year % 4) == 0));
}
// day_of_year()
// Converts a year (for example: 2010), a month (1-12), and a day (1-31)
// into the day of the year.
// Returns zero on failure.
//
int day_of_year(
int year,
int month,
int day
) {
int result = is_leap_year( year ) ? 1 : 0;
if ((month < 1)
|| (month > 12)
|| (day < 1)
|| (day > (days_per_month[ month ] + result)))
return 0;
while (--month)
result += days_per_month[ month ];
result += day;
return result;
}
// th()
// Return the proper ordinal suffix to a number -- "st", "nd", "rd", or "th".
//
const char* th( int n )
{
switch (n % 10)
{
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
}
int main() {
int year, month, day;
cout << "What year were you born? " << flush;
cin >> year;
cout << "What month were you born (1..12)? " << flush;
cin >> month;
cout << "What day were you born? " << flush;
cin >> day;
day = mycalendar::day_of_year( year, month, day );
cout << "You were born on the "
<< day
<< mycalendar::th( day )
<< " day of the year "
<< year
<< ".\n";
return 0;
}
|