头歌答案c++打印日历
时间: 2023-12-13 15:04:34 浏览: 54
以下是C++打印日历的代码,可以根据用户输入的年份和月份打印出对应的日历:
```c++
#include <iostream>
using namespace std;
int main() {
int year, month, day = 1;
int month_day[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
string week[7] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
cout << "Please enter the year: ";
cin >> year;
cout << "Please enter the month: ";
cin >> month;
// 判断是否为闰年
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
month_day[1] = 29;
}
// 计算当月第一天是星期几
int week_day = (year - 1 + (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400 + day) % 7;
// 打印日历表头
cout << "-----------------------------" << endl;
cout << " " << year << "年" << month << "月" << endl;
cout << "-----------------------------" << endl;
for (int i = 0; i < 7; i++) {
cout << week[i] << " ";
}
cout << endl;
// 打印日历
for (int i = 0; i < week_day; i++) {
cout << " ";
}
for (int i = 1; i <= month_day[month - 1]; i++) {
printf("%4d", i);
if ((i + week_day) % 7 == 0) {
cout << endl;
}
}
cout << endl << "-----------------------------" << endl;
return 0;
}
```