万年历 要求:模仿现实生活中的万年历。功能核心是判断闰年和根据给定日期计算对应星期,并按照合适的方式输出日历。 基本功能: 1.日历显示功能。根据系统日期进行初始化,如果没有任何输入则会显示系统所在月份的月历,并突出显示当前日期。此外,显示界面有用户提示指南说明部分。 2.日历查询、闰年判断功能。输入日期进行查询后将显示日期所在月份的月历,并突出显示当前日期。此外还将显示查询日期所在年份是否是闰年。 3.支持键盘操作。可通过键盘调整年、月、日,并显示调整过后的日期。还可通过键盘操作复位到系统所在日期等。
时间: 2024-02-16 07:04:07 浏览: 20
实现一个完整的万年历需要涉及到很多细节,以下是一个基本的实现。
```c++
#include <iostream>
#include <ctime>
#include <iomanip>
using namespace std;
int getWeekday(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;
}
bool isLeapYear(int year) {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
return true;
}
return false;
}
void printMonth(int year, int month) {
cout << "========== " << year << "年" << month << "月 ==========" << endl;
cout << "日\t一\t二\t三\t四\t五\t六" << endl;
int daysInMonth;
if (month == 2) {
if (isLeapYear(year)) {
daysInMonth = 29;
} else {
daysInMonth = 28;
}
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
daysInMonth = 30;
} else {
daysInMonth = 31;
}
int weekday = getWeekday(year, month, 1);
for (int i = 0; i < weekday; i++) {
cout << "\t";
}
for (int i = 1; i <= daysInMonth; i++) {
cout << i << "\t";
if ((i + weekday) % 7 == 0) {
cout << endl;
}
}
cout << endl;
}
int main() {
time_t now = time(nullptr);
tm* ptm = localtime(&now);
int year = ptm->tm_year + 1900;
int month = ptm->tm_mon + 1;
int day = ptm->tm_mday;
cout << "===== 万年历 =====" << endl;
cout << "当前日期:" << year << "年" << month << "月" << day << "日" << endl;
printMonth(year, month);
while (true) {
cout << "请输入命令(h帮助):";
char command;
cin >> command;
if (command == 'h') {
cout << "帮助:\nq-退出\np-上一个月\nn-下一个月\ny-前一年\nx-后一年\nr-返回今天" << endl;
} else if (command == 'q') {
break;
} else if (command == 'p') {
if (month == 1) {
month = 12;
year--;
} else {
month--;
}
printMonth(year, month);
} else if (command == 'n') {
if (month == 12) {
month = 1;
year++;
} else {
month++;
}
printMonth(year, month);
} else if (command == 'y') {
year--;
printMonth(year, month);
} else if (command == 'x') {
year++;
printMonth(year, month);
} else if (command == 'r') {
time_t now = time(nullptr);
tm* ptm = localtime(&now);
year = ptm->tm_year + 1900;
month = ptm->tm_mon + 1;
printMonth(year, month);
} else {
cout << "无效命令,请输入h查看帮助" << endl;
}
}
return 0;
}
```
该程序初始化时会显示当前日期所在月份的月历,并提示可用的命令。用户可以输入命令进行操作,如p(上一个月)、n(下一个月)、y(前一年)、x(后一年)、r(返回今天)等。同时,用户也可以输入一个日期,程序会显示该日期所在月份的月历,并显示该年份是否是闰年。