以下是使用C++编写的双列展示日历的示例代码:你可以根据需要调用 printCalendar() 函数来打印指定年份和月份的日历。该函数会以两列表示月份的日历,并按照星期几进行对齐显示。
- #include <iostream>
- #include <iomanip>
- // 获取某个月的总天数
- int getMonthDays(int year, int month) {
- int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
- // 对于闰年的二月,天数为29
- if (month == 2 && (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))) {
- return 29;
- }
- return days[month - 1];
- }
- // 获取某个月的第一天是星期几
- int getFirstDayOfWeek(int year, int month) {
- // Zeller's Congruence算法
- if (month < 3) {
- month += 12;
- year--;
- }
- int c = year / 100;
- int y = year - c * 100;
- int m = month;
- int d = 1;
- int w = (y + y/4 + c/4 - 2*c + 26*(m+1)/10 + d - 1) % 7;
- if (w < 0) {
- w += 7;
- }
- return w;
- }
- // 打印日历
- void printCalendar(int year, int month) {
- // 获取该月的总天数
- int days = getMonthDays(year, month);
- // 获取该月的第一天是星期几
- int firstDayOfWeek = getFirstDayOfWeek(year, month);
- std::cout << std::setw(12) << " " << year << "年" << month << "月" << std::endl;
- std::cout << "日 一 二 三 四 五 六" << std::endl;
- // 打印第一行的空格
- for (int i = 0; i < firstDayOfWeek; i++) {
- std::cout << " ";
- }
- // 打印日历内容
- for (int i = 1; i <= days; i++) {
- std::cout << std::setw(2) << i << " ";
- if ((firstDayOfWeek + i) % 7 == 0) {
- std::cout << std::endl;
- }
- }
- std::cout << std::endl;
- }
- int main() {
- int year, month;
- std::cout << "请输入年份和月份(用空格分隔):";
- std::cin >> year >> month;
- printCalendar(year, month);
- return 0;
- }
"小礼物走一走,来肥宅自学平台支持我"
评论区
共条评论
- 这篇文章还没有收到评论,赶紧来抢沙发吧~
首页上页1下页尾页