代码
#include <iostream>
#include<iomanip>
#include<windows.h>
#include<string>
#include<vector>
#include<array>
using namespace std;
bool judge_runnian(int year) {/*judge_runnian:判断是否是闰年*/
bool ifrun;
if ((year % 4 == 0) & (year % 100 != 0)) {
ifrun = true;
}
else if ((year % 4 == 0) & (year % 400 == 0)) {
ifrun = true;
}
else {
ifrun = false;
}
return ifrun;
}
vector<string> splitstring(const string s, const string c)//利用空格分隔字符串
{
string::size_type pos1, pos2;//::标明类的变量
vector<string> v;
pos1 = 0;
pos2 = s.find(c);
while (string::npos != pos2) {
v.push_back(s.substr(pos1, pos2 - pos1));
pos1 = pos2 + c.size();
pos2 = s.find(c, pos1);
}
if (pos1 != s.length())
v.push_back(s.substr(pos1));
return v;
}
int main()//主函数代码如下
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_GREEN);//设置cmd窗口字体颜色
cout << "请输入年月(以一个空格分开)" << endl;
string day;
getline(cin, day);
vector<string> newday;
newday = splitstring(day, " ");
int year, month;
year = atoi(newday[0].c_str());
month = atoi(newday[1].c_str());
cout << year << "年" << month << "月日历如下:\n";
// 计算月初是星期几
int year0 = 2000; // 与2000年1月作对比
int gap = year - year0;
vector<int> array1;
for (int i = year0; i < year; i++) {
array1.push_back(i);
}
int run_num = 0;
for (int i = 0; i < array1.size(); i++)
{
int j = judge_runnian(array1[i]);
run_num += j;
}
int run = judge_runnian(year);
int feb = 28 + run;
int day_gap = 0;
int year_gap = gap * 365 + run_num; // 计算年差天数
int array2[] = { 31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int month_gap = 0;
for (int i = 0; i + 1 < month; i++) {
month_gap += array2[i]; // 计算月差天数
}
day_gap = year_gap + month_gap;
int week = day_gap % 7; // 天数差除以7,即可知道1号的位置
int star = 5 + week; // 2000年1月1号是星期六,前面带5颗星* * * * * 1 2
if (star >= 7) {
star -= 7;
}
// 打印月历
for (int i = 0; i < star + array2[month-1]; i++) {
if (i < star) {
cout << " * ";// 1月前面的空缺用*来填补
}
else {
cout << setw(3) << i + 1 - star;
cout << " ";
}
if ((i + 1) % 7 == 0)
cout << endl;
}
return 0;
};
};
演示