#include #include using namespace std;

int daysInMonth(int year, int month) { //计算该月的天数 if (month == 2) { if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { //闰年判断 return 29; } else { return 28; } } else if (month == 4 || month == 6 || month == 9 || month == 11) { return 30; } else { return 31; } }

int weekDay(int year, int month, int day) { //计算该日期的星期几 struct tm timeinfo = { 0 }; timeinfo.tm_year = year - 1900; timeinfo.tm_mon = month - 1; timeinfo.tm_mday = day; mktime(&timeinfo); return timeinfo.tm_wday; }

void printMonth(int year, int month) { //输出月份日历 int days = daysInMonth(year, month); int week = weekDay(year, month, 1); cout << "-----------------" << endl; cout << " Sun Mon Tue Wed Thu Fri Sat" << endl; cout << "-----------------" << endl; for (int i = 0; i < week; i++) { cout << " "; } for (int i = 1; i <= days; i++) { cout << " "; cout.width(2); cout.fill('0'); cout << i; if ((i + week) % 7 == 0) { cout << endl; } } if ((days + week) % 7 != 0) { cout << endl; } cout << "-----------------" << endl; }

void printYear(int year) { //输出整年日历 for (int i = 1; i <= 12; i++) { cout << " " << year << "年" << i << "月 " << endl; printMonth(year, i); cout << endl; } }

int main() { int year, month, day; time_t rawtime; struct tm* timeinfo; time(&rawtime); timeinfo = localtime(&rawtime); int currentMonth = timeinfo->tm_mon + 1; cout << "请输入年份:"; cin >> year; cout << "请输入月份:"; cin >> month; if (month < 1 || month > 12) { cout << "输入错误!" << endl; return 0; } cout << endl; if (year < 1900 || year > 2100) { cout << "输入错误!" << endl; return 0; } printMonth(year, month); if (month == currentMonth) { cout << "当前是" << year << "年" << month << "月" << endl; } cout << endl; cout << "是否输出整年日历?(y/n)"; char choice; cin >> choice; if (choice == 'y' || choice == 'Y') { printYear(year); } cout << "请输入日期:"; cin >> day; if (day < 1 || day > daysInMonth(year, month)) { cout << "输入错误!" << endl; return 0; } cout << "该日期是" << year << "年" << month << "月" << day << "日,星期"; switch (weekDay(year, month, day)) { case 0: cout << "日"; break; case 1: cout << "一"; break; case 2: cout << "二"; break; case 3: cout << "三"; break; case 4: cout << "四"; break; case 5: cout << "五"; break; case 6: cout << "六"; break; } cout << endl; return 0; }


原文地址: https://www.cveoy.top/t/topic/oRvB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录