#include #include // The following is necessary if and only if you're using an older // compiler which doesn't recognize type "bool". If used in combination // with a compiler which does recognize "bool", an error will result. // typedef enum { false = 0, true = 1 } bool; // returns true if the year is a leap year bool year_is_leap (int year) { return ((year % 4) == 0) && (((year % 100) != 0) || ((year % 400) == 0)); } int days_in_year (int year) { if (year_is_leap(year)) { return 366; } else { return 365; } } // January = month 1, February = month 2, etc. int days_in_month (int month, int year) { const int days_table [12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // look after the special case if ((month == 2) && year_is_leap(year)) { return 29; } return days_table[month - 1]; } void day_number_to_day_and_month (int day_number, int year, int &day, int &month) { month = 1; // start off by assuming January // while we've enough days left to get through another month... while (day_number > days_in_month (month, year)) { // advance to next month and reduce the number of days left to play with day_number -= days_in_month (month, year); month++; } // any days left over at this point are days into the month day = day_number; } int day_and_month_to_day_number (int day, int month, int year) { int day_number = 0, i; // add up all the days in preceding months for (i = 1; i < month; i++) { day_number += days_in_month (i, year); } // add in the number of days into the month day_number += day; return day_number; } int main () { int day, month, year, day_number, option; for (;;) { cout << endl << "Enter option" << endl << " 1 = day number to dd/mm" << endl << " 2 = dd/mm to day number" << endl << " 3 = quit" << endl << ": "; cin >> option; if (option == 1) { cout << endl << "Enter day number and year: "; cin >> day_number >> year; if ((year < 1500) || (day_number < 1) || (day_number > days_in_year(year))) { cout << "The data entered is invalid." << endl; } else { day_number_to_day_and_month (day_number, year, day, month); cout << "Day: " << day << " Month: " << month << endl; } } else if (option == 2) { cout << endl << "Enter day, month, and year: "; cin >> day >> month >> year; if ((year < 1500) || (month < 1) || (month > 12) || (day < 1)||(day > days_in_month(month, year))) { cout << "The data entered is invalid." << endl; } else { cout << " Day number: " << day_and_month_to_day_number (day, month, year) << endl; } } else if (option == 3) { return 0; // we're all done } else { cout << endl << "Illegal option ignored." << endl; } } // end for(;;) }