【C/C++ 09】万年历

一、题目

输入一个年份,以日历的格式打印这一年的所有天数,需要正确的表示每一天是周几。

二、算法

以公元1年1月1日作为万年历的起始日期,公元1年1月1日是周一,所以算法的核心就是就算某一天距离起始日期的天数差,然后根据天数差取模就能得到周几。

拿到输入的年份后,循环打印每个月的日历表格,每个月都计算出这个月第一条距离万年历其实日期的天数差,便能得到当月第一天是周几,然后根据当月的总天数,便能打印出当月的日历表。

三、代码

cpp 复制代码
#define _CRT_SECURE_NO_WARNINGS 1

// 起始日期:公元1年1月1日,周一

#include <iostream>
#include <vector>
using namespace std;

vector<int> g_monthDays = { 31, 28, 31, 30, 31, 30,
						    31, 31, 30, 31, 30, 31 };

bool LeapYear(int year)
{
	if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
		return true;
	return false;
}

int GetMonthDays(int year, int month)
{
	if (LeapYear(year) && month == 2)
		return 29;
	return g_monthDays[month - 1];
}

int GetYearDays(int year)
{
	if (LeapYear(year))
		return 366;
	return 365;
}

int GetDays(int year, int month, int day)
{
	int sum = 0;
	for (int i = 1; i < year; ++i)
	{
		sum += GetYearDays(i);
	}
	for (int i = 1; i < month; ++i)
	{
		sum += GetMonthDays(year, i);
	}
	sum += day;
	return sum;
}

void PrintMonth(int year, int month)
{
	printf("|-------------- %d 年 %02d 月 -------------|\n", year, month);
	cout << "|------------------------------------------|" << endl;
	cout << "| 周日 " << " 周一 " << " 周二 " << " 周三 " << " 周四 " << " 周五 " << " 周六 " << "|" << endl;

	int monthDays = GetMonthDays(year, month);
	int firstDays = GetDays(year, month, 1);

	int weekday = firstDays % 7;
	cout << "|";
	for (int i = 0; i < weekday; ++i)
		cout << "      ";
	for (int i = 1; i <= monthDays; ++i)
	{
		printf("  %02d  ", i);
		weekday = (weekday + 1) % 7;
		if (weekday == 0)
			cout << "|" << endl << "|";
	}
	if (weekday != 0)
	{
		for (int i = 0; i < 7 - weekday; ++i)
			cout << "      ";
		cout << "|" << endl << "|";
	}
	cout << "------------------------------------------|" << endl;
	cout << endl << endl;
}

int main()
{
	cout << "请输入年份:";
	int year;
	cin >> year;

	for (int i = 1; i <= 12; ++i)
	{
		PrintMonth(year, i);
	}

	return 0;
}

四、测试

共12个月,截取部分月份。

相关推荐
前进的李工7 分钟前
LeetCode hot100:094 二叉树的中序遍历:从递归到迭代的完整指南
python·算法·leetcode·链表·二叉树
麦麦大数据1 小时前
F049 知识图谱双算法推荐在线学习系统vue+flask+neo4j之BS架构开题论文全源码
学习·算法·知识图谱·推荐算法·开题报告·学习系统·计算机毕业设计展示
喵个咪1 小时前
Qt 优雅实现线程安全单例模式(模板化 + 自动清理)
c++·后端·qt
兩尛1 小时前
215. 数组中的第K个最大元素
数据结构·算法·排序算法
952361 小时前
数据结构-堆
java·数据结构·学习·算法
吃着火锅x唱着歌2 小时前
LeetCode 面试题 16.24.数对和
算法·leetcode·职场和发展
不会编程的小寒2 小时前
数据结构 2.0
数据结构·算法
欧阳x天2 小时前
C++入门(一)
c++
专注VB编程开发20年2 小时前
图片转矢量图(提取轮廓线条)Potrace:一个基于多边形的位图轮廓矢量化算法(translation)
算法·图片转矢量
小张成长计划..2 小时前
【C++】:priority_queue的理解,使用和模拟实现
c++