
实现一个C++万年历程序,核心在于日期计算的准确性与输出格式的清晰美观。这类程序通常支持查询任意年月的日历,包含闰年判断、每月天数计算、某年某月某日是星期几的推算,并以表格形式输出当月日历。
正确判断闰年是日期计算的前提。公历年份满足以下条件之一即为闰年:
根据是否为闰年,2月天数为29或28天。其他月份天数固定。可用数组存储每月天数:
int daysInMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (isLeap(year)) daysInMonth[2] = 29;
常用基姆拉尔森公式计算某年某月1日是星期几,适用于公历:
立即学习“C++免费学习笔记(深入)”;
int weekday = (day + 2 * month + 3 * (month + 1) / 5 + year
+ year / 4 - year / 100 + year / 400) % 7;
// 注意:若月份为1或2,需视为上一年的13或14月
if (month < 3) {
month += 12;
year--;
}
计算结果中,0表示星期一,1表示星期二……6表示星期日(可按需调整)。
输出时需对齐列宽,通常用
setw()
示例代码片段:
#include <iomanip>
#include <iostream>
using namespace std;
<p>void printCalendar(int year, int month) {
cout << "\n " << year << " 年 " << month << " 月\n";
cout << "一 二 三 四 五 六 日\n";</p><pre class='brush:php;toolbar:false;'>int firstDay = getWeekday(year, month, 1); // 获取1号是星期几(0=周一)
int days = getDaysInMonth(year, month);
// 输出前置空格
for (int i = 0; i < firstDay; i++) {
cout << " ";
}
// 输出日期
for (int day = 1; day <= days; day++) {
cout << setw(2) << day << " ";
if ((day + firstDay) % 7 == 0) cout << "\n";
}
cout << "\n";}
一个实用的万年历程序可扩展以下功能:
注意处理用户输入合法性,如年份范围、月份范围等。
基本上就这些,核心是日期算法正确,输出对齐清晰。C++中利用
iomanip
以上就是C++万年历程序实现 日期计算显示格式控制的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号