【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个月,截取部分月份。

相关推荐
软件算法开发8 小时前
基于卷尾猴优化的LSTM深度学习网络模型(CSA-LSTM)的一维时间序列预测算法matlab仿真
深度学习·算法·matlab·lstm·一维时间序列预测·卷尾猴优化·csa-lstm
高洁018 小时前
知识图谱如何在制造业实际落地应用
深度学习·算法·机器学习·数据挖掘·知识图谱
BHXDML8 小时前
数据结构:(二)逻辑之门——栈与队列
java·数据结构·算法
Stack Overflow?Tan908 小时前
c++constexpr
开发语言·c++
进击的小头8 小时前
行为型模式:观察者模式
c语言·观察者模式
晚风吹长发8 小时前
初步了解Linux中的信号捕捉
linux·运维·服务器·c++·算法·进程·x信号
机器学习之心8 小时前
MATLAB基于GA-ELM与NSGA-Ⅱ算法的42CrMo表面激光熔覆参数多目标优化
算法·matlab·ga-elm
TracyCoder1238 小时前
LeetCode Hot100(17/100)——240. 搜索二维矩阵 II
算法·leetcode
FJW0208148 小时前
haproxy的调度算法
算法
小程同学>o<8 小时前
嵌入式之C/C++(二)内存
c语言·开发语言·c++·笔记·嵌入式软件·面试题库