该c++++万年历程序通过蔡勒公式计算某月1日是星期几,结合闰年判断和每月天数计算,实现指定年月的日历输出,支持格式化对齐和清晰的表格布局,最终以可读性强的方式展示结果,完整实现了基本日历功能并具备良好的扩展性。

实现一个C++万年历程序,核心在于日期的计算(如判断闰年、计算某年某月的天数、确定某天是星期几)以及输出格式的美观控制。下面是一个实用、可运行的万年历程序实现,包含关键逻辑说明和格式化输出。
我们使用蔡勒公式(Zeller's Congruence)来计算某月1日是星期几:
int getWeekDay(int year, int month, int day) {
if (month < 3) {
month += 12;
year--;
}
int k = year % 100;
int j = year / 100;
int h = (day + (13 * (month + 1)) / 5 + k + k / 4 + j / 4 - 2 * j) % 7;
// 返回 0=Sunday, 1=Monday, ..., 6=Saturday
return (h + 5) % 7 + 1; // 调整为 1=Monday, 2=Tuesday, ..., 7=Sunday
}注意:这里我们调整为返回1~7,1表示周一,7表示周日,方便排版控制。
bool isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}int getDaysInMonth(int year, int month) {
static int days[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (month == 2 && isLeapYear(year)) {
return 29;
}
return days[month];
}void printCalendar(int year, int month) {
const char* months[] = {"", "January", "February", "March", "April",
"May", "June", "July", "August", "September",
"October", "November", "December"};
cout << "\n " << months[month] << " " << year << endl;
cout << " Mon Tue Wed Thu Fri Sat Sun" << endl;
// 获取当月1号是星期几(1=Mon, 7=Sun)
int weekday = getWeekDay(year, month, 1);
// 打印前置空格
for (int i = 1; i < weekday; i++) {
cout << " ";
}
int days = getDaysInMonth(year, month);
for (int day = 1; day <= days; day++) {
printf("%5d", day);
if ((weekday + day - 1) % 7 == 0) { // 换行:每周7天
cout << endl;
}
}
if ((weekday + days - 1) % 7 != 0) {
cout << endl;
}
}#include <iostream>
#include <cstdio>
using namespace std;
int main() {
int year, month;
cout << "Enter year and month (e.g., 2025 3): ";
cin >> year >> month;
if (month < 1 || month > 12) {
cout << "Invalid month!" << endl;
return 1;
}
printCalendar(year, month);
return 0;
}输入:
立即学习“C++免费学习笔记(深入)”;
Enter year and month: 2025 3
输出:
March 2025
Mon Tue Wed Thu Fri Sat Sun
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31这个C++万年历程序的关键在于:
printf
%5d
基本上就这些,不复杂但容易忽略细节,比如星期偏移和闰年判断。
以上就是C++实现万年历程序 日期计算与显示格式控制的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号