题目6万年历1问题描述编写一个万年历系统输入任意年份显示该年的12个月份;输入任意年份和月份显示该年月日历。2设计要求1要求每个面板输出整个月份不可分段显示超过应能够自动分屏显示提示可通过if语句控制输出行数的多少2能对闰年进行检测与处理提示通过取4的余数来判断是否为闰年。3按照日历的格式每行自动显示7位数提示类似于1的过程通过if语句来实现4能自动调用系统时间显示出当前时间所在的月份可有可无提示
3.实现思路: (1)根据输入的年份和月份,计算该月的天数和起始星期几 (2)根据起始星期几,输出日历表格,每行7个数字,超过则自动分行 (3)根据输入的年份,检测是否为闰年,计算2月的天数 (4)根据当前系统时间,自动显示当前月份 (5)对输入错误进行容错处理,如输入32号等 4.代码实现:
#include
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/hoGR 著作权归作者所有。请勿转载和采集!