【C++】日期类实现,与日期计算相关OJ题
文章目录
- 日期类的设计
- 日期计算相关OJ题
- HJ73 计算日期到天数转换
- KY111 日期差值
- KY222 打印日期
- KY258 日期累加
在软件开发中,处理日期是一项常见的任务。为了方便地操作日期,我们可以使用C++编程语言来创建一个简单的日期类。在本文中,我们将介绍如何使用C++实现一个基本的日期类,包括日期的加减、大小比较等功能。
日期类的设计
下面是日期类的基本实现代码:
#pragma once
#include<iostream>
using namespace std;class Date {
public:// 获取某年某月的天数int GetMonthDay(const int year, const int month);// 构造函数Date(int year = 1900, int month = 1, int day = 1);// 拷贝构造函数Date(const Date& d);// 析构函数~Date();// 打印日期void print()const;// 赋值运算符重载Date& operator=(const Date& d);// +=运算符重载Date& operator+=(const int day);// +运算符重载Date operator+(const int day);// -=运算符重载Date& operator-=(int day);// -运算符重载Date operator-(int day);// 计算两个日期之间的天数差int operator-(const Date& d) const;// ++前置运算符重载Date& operator++();// ++后置运算符重载Date operator++(int);// --前置运算符重载Date& operator--();// --后置运算符重载Date operator--(int);// 大于运算符重载bool operator>(const Date& d) const;// 等于运算符重载bool operator==(const Date& d) const;// 大于等于运算符重载bool operator >= (const Date& d) const;// 小于运算符重载bool operator < (const Date& d) const;// 小于等于运算符重载bool operator <= (const Date& d) const;// 不等于运算符重载bool operator != (const Date& d) const;// 地址运算符重载const Date* operator & () const;// 输出流运算符重载friend ostream& operator << (ostream& out, const Date& d);// 输入流运算符重载friend istream& operator >> (istream& in, Date& d);private:int _year; // 年int _month; // 月int _day; // 日
};// 获取某年某月的天数
int Date::GetMonthDay(const int year, const int month) {int monthDay[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };if (2 == month && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))) {return 29;}return monthDay[month];
}// 构造函数
Date::Date(int year, int month, int day) {if ((year < 1) || (month < 1) || (month > 12) || (day < 1) || (day > GetMonthDay(year, month))) {cout << "非法日期:" << endl;}_year = year;_month = month;_day = day;
}// 拷贝构造函数
Date::Date(const Date& d) {_year = d._year;_month = d._month;_day = d._day;
}// 析构函数
Date::~Date() {_year = 1900;_month = 1;_day = 1;
}// 打印日期
void Date::print()const {cout << _year << "/" << _month << "/" << _day << endl;
}// 赋值运算符重载
Date& Date::operator=(const Date& d) {if (this != &d) {_day = d._day;_month = d._month;_year = d._year;}return *this;
}// +=运算符重载
Date& Date::operator+=(const int day) {_day += day;while (_day > GetMonthDay(_year, _month)) {_day -= GetMonthDay(_year, _month);++_month;if (_month == 13) {++_year;_month = 1;}}return *this;
}// +运算符重载
Date Date::operator+(const int day) {Date tmp(*this);tmp += day;return tmp;
}// -=运算符重载
Date& Date::operator-=(int day) {_day -= day;while (_day < 0) {--_month;if (_month == 0) {--_year;_month = 12;}_day += GetMonthDay(_year, _month);}return *this;
}// -运算符重载
Date Date::operator-(int day) {Date tmp(*this);tmp -= day;return tmp;
}// 计算两个日期之间的天数差
int Date::operator-(const Date& d) const {Date BigDate = *this;Date SmallDate = d;if (SmallDate > BigDate) {BigDate = d;SmallDate = *this;}int count = 0;while (SmallDate != BigDate) {++SmallDate;++count;}return count;
}// ++前置运算符重载
Date& Date::operator++() {*this += 1;return *this;
}// ++后置运算符重载
Date Date::operator++(int) {Date tmp(*this);*this += 1;return tmp;
}// --前置运算符重载
Date& Date::operator--() {*this -= 1;return *this;
}// --后置运算符重载
Date Date::operator--(int) {Date tmp(*this);*this -= 1;return tmp;
}// 大于运算符重载
bool Date::operator>(const Date& d) const {if (_year > d._year || (_year == d._year && _month > d._month) || (_year == d._year && _month == d._month && _day > d._day)) {return true;}return false;
}// 等于运算符重载
bool Date::operator==(const Date& d) const {return _year == d._year && _month == d._month && _day == d._day;
}// 大于等于运算符重载
bool Date::operator >= (const Date& d) const {return (*this > d) || (*this == d);
}// 小于运算符重载
bool Date::operator < (const Date& d) const {return !(*this >= d);
}// 小于等于运算符重载
bool Date::operator <= (const Date& d) const {return !(*this > d);
}// 不等于运算符重载
bool Date::operator != (const Date& d) const {return !(*this == d);
}// 地址运算符重载
const Date* Date::operator & () const {return this;
}// 输出流运算符重载
ostream& operator << (ostream& out, const Date& d) {out << d._year << "/" << d._month << "/" << d._day;return out;
}// 输入流运算符重载
istream& operator >> (istream& in, Date& d) {in >> d._year;in >> d._month;in >> d._day;return in;
}
上面的代码实现了日期类的基本功能,包括构造函数、加减运算符重载、比较运算符重载、输入输出流运算符重载等。
下面是主函数用于测试代码功能:
int main() {// 创建日期对象并打印Date d1(2023, 11, 13);cout << "日期1:";d1.print();// 拷贝构造函数测试Date d2(d1);cout << "日期2(拷贝构造):";d2.print();// 赋值运算符重载测试Date d3 = d1;cout << "日期3(赋值运算符重载):";d3.print();// += 运算符重载测试d1 += 10;cout << "日期1(+=运算符重载后):";d1.print();// + 运算符重载测试Date d4 = d2 + 5;cout << "日期4(+运算符重载):";d4.print();// -= 运算符重载测试d2 -= 3;cout << "日期2(-=运算符重载后):";d2.print();// - 运算符重载测试Date d5 = d3 - 7;cout << "日期5(-运算符重载):";d5.print();// - 运算符重载测试int diff = d5 - d4;cout << "日期4和日期5之间的天数差:" << diff << endl;// ++ 前置运算符重载测试++d1;cout << "日期1(++前置运算符重载后):";d1.print();// ++ 后置运算符重载测试Date d6 = d2++;cout << "日期6(++后置运算符重载):";d6.print();cout << "日期2(++后置运算符重载后):";d2.print();// -- 前置运算符重载测试--d3;cout << "日期3(--前置运算符重载后):";d3.print();// -- 后置运算符重载测试Date d7 = d4--;cout << "日期7(--后置运算符重载):";d7.print();cout << "日期4(--后置运算符重载后):";d4.print();// 大于运算符重载测试cout << "日期5大于日期6吗?" << (d5 > d6 ? "是" : "否") << endl;// 等于运算符重载测试cout << "日期1等于日期2吗?" << (d1 == d2 ? "是" : "否") << endl;// 不等于运算符重载测试cout << "日期3不等于日期4吗?" << (d3 != d4 ? "是" : "否") << endl;// 输出流运算符重载测试cout << "日期1的输出流运算符重载:" << d1 << endl;// 输入流运算符重载测试Date d8;cout << "请输入一个日期(年 月 日):";cin >> d8;cout << "您输入的日期为:" << d8 << endl;return 0;
}
C++实现一个简单的日期类,包括日期的加减、大小比较等功能。日期类的实现可以帮助我们更方便地处理日期,提高代码的可读性和可维护性。
日期计算相关OJ题
HJ73 计算日期到天数转换
https://www.nowcoder.com/practice/769d45d455fe40b385ba32f97e7bcded?tpId=37&&tqId=21296&rp=1&ru=/activity/oj&qru=/ta/huawei/question-ranking
#include <iostream>
using namespace std;int main() {int month[13] = {0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};int y, m, d;cin >> y >> m >> d;int day = d;if (2 < m && ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0))){day += 1;}day += month[m];cout << day << endl;
}
KY111 日期差值
https://www.nowcoder.com/practice/ccb7383c76fc48d2bbc27a2a6319631c?tpId=62&&tqId=29468&rp=1&ru=/activity/oj&qru=/ta/sju-kaoyan/question-ranking
#include <iostream>
#include <string>
using namespace std;// 判断是否为闰年
bool isLeapYear(int year)
{return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}// 获取某年某月的天数
int getDaysOfMonth(int year, int month)
{int daysOfMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};if (month == 2 && isLeapYear(year)) {return 29;}return daysOfMonth[month];
}// 计算日期距离公元0年的天数
int getDaysFromZero(int year, int month, int day)
{int days = 0;for (int y = 1; y < year; ++y) {days += isLeapYear(y) ? 366 : 365;}for (int m = 1; m < month; ++m) {days += getDaysOfMonth(year, m);}days += day;return days;
}// 计算两个日期之间的天数差值
int getDaysDiff(const string& date1, const string& date2)
{int year1, month1, day1, year2, month2, day2;sscanf(date1.c_str(), "%4d%2d%2d", &year1, &month1, &day1);sscanf(date2.c_str(), "%4d%2d%2d", &year2, &month2, &day2);int days1 = getDaysFromZero(year1, month1, day1);int days2 = getDaysFromZero(year2, month2, day2);return abs(days2 - days1) + 1;
}int main()
{string date1, date2;while (cin >> date1 >> date2) {int daysDiff = getDaysDiff(date1, date2);cout << daysDiff << endl;}return 0;
}
KY222 打印日期
https://www.nowcoder.com/practice/b1f7a77416194fd3abd63737cdfcf82b?tpId=69&&tqId=29669&rp=1&ru=/activity/oj&qru=/ta/hust-kaoyan/question-ranking
#include <iostream>
using namespace std;bool isLeapYear(int year)
{return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}int getMonthDay(int year, int month)
{int daysOfMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};if (month == 2 && isLeapYear(year)) {return 29;}return daysOfMonth[month];
}int main() {int year, day;while (cin >> year >> day) { int month = 1;while (day > getMonthDay(year, month)){day -= getMonthDay(year, month);++month;}printf("%4d-%02d-%02d\n", year, month, day);}
}
KY258 日期累加
https://www.nowcoder.com/practice/eebb2983b7bf40408a1360efb33f9e5d?tpId=40&&tqId=31013&rp=1&ru=/activity/oj&qru=/ta/kaoyan/question-ranking
#include <iostream>
using namespace std;bool isLeapYear(int year)
{return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}int getMonthDay(int year, int month)
{int daysOfMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};if (month == 2 && isLeapYear(year)) {return 29;}return daysOfMonth[month];
}
int main() {int t, year, month, day, add;cin >> t;while (t--) { // 注意 while 处理多个 casecin >> year >> month >> day >> add;day += add;while (day > getMonthDay(year, month)){day -= getMonthDay(year, month);++month;if (13 == month){month = 1;++year;}}printf("%4d-%02d-%02d\n", year, month, day);}
}
相关文章:

【C++】日期类实现,与日期计算相关OJ题
文章目录 日期类的设计日期计算相关OJ题HJ73 计算日期到天数转换KY111 日期差值KY222 打印日期KY258 日期累加 在软件开发中,处理日期是一项常见的任务。为了方便地操作日期,我们可以使用C编程语言来创建一个简单的日期类。在本文中,我们将介…...

前端404页面的制作
1、背景 前端开发经常遇到输入路径不存在的问题,为此,把之前项目的404拿出来供大家参考。代码很简单,适合新手入手,效果如下: 2、代码引用的是element-plus框架 <template><div><el-result icon"…...

深兰科技轮腿家用AI机器人荣获“2023年度城市更新科创大奖”
近日,“2023金砖论坛第五季金立方城市更新科创大会”在上海举行,会上发布了《第12届金砖价值榜》,深兰科技研发出品的轮腿式家用AI机器人(兰宝),因其AI技术的创新性应用,荣获了“2023年度城市更新科创大奖”。 在10月2…...
669.修剪二叉树
原题链接:669.修剪二叉树 全代码: class Solution { public:TreeNode* trimBST(TreeNode* root, int low, int high) {if (root nullptr ) return nullptr;if (root->val < low) {TreeNode* right trimBST(root->right, low, high); // 寻找符合区间[l…...

论文绘图-机器学习100张模型图
在现代学术研究和技术展示中,高质量的图表和模型结构图是至关重要的。这尤其在机器学习领域更为显著,一个领域以其复杂的算法和复杂的数据结构而闻名。机器学习是一种使用统计技术使计算机系统能够从数据中学习和改进其任务执行的方法,而有效…...

PHP项目学习笔记-萤火商城-增加一个模块(表涉及到的操作和文件)
背景 是在store的后台添加一个页面,显示的如满意度调查的页面 在router.config.js里面配置一个新的菜单 路径:yoshop2.0-store\src\config\router.config.js 代码如下,很简单,定义了这菜单点击的时候进入的页面,和下面…...
如何用Java设计自动售货机?
如何用Java设计自动售货机?是大多在高级Java开发人员面试中经常被问到的好问题之一。在典型的编码面试中,你会得到一个问题描述来开发一个售货机,在有限的时间内,通常2到3小时内,你需要在Java中编写设计文档、工作代码和单元测试。这种Java面试的一个关键优势是可以一次测试候…...

JAVA数据代码示例
首先,我们需要导入一些必要的Java库 java import java.net.URL; import java.net.HttpURLConnection; import java.io.BufferedReader; import java.io.InputStreamReader; 然后,我们可以创建一个URL对象,表示我们要爬取的网页的URL。 jav…...
github常用搜索指令
一、常用搜索指令 以下指令可分开用,也可组合使用 根据关键字搜索 in:name xx继上一步:指定开发语言 language:Java in:name XX language:Java继上一步,指定更新日期 pushed:>2022-06-06 in:name XX language:Java pushed:>2022-0…...

为什么esp8266刷入了固件,无法接受AT指令
我遇到的解决方法是:是串口调试助手出了问题。所以需要更换一个串口调试助手软件。 上面这个就是我换了的软件 在开发的时候,经常会遇到软件故障,导致正确的方法,但是没有效果,好比以前用盗版的8.7版本的Proteus模拟…...
Scala---字符串、集合
一、字符串 StringStringBuilder 可变string操作方法举例 比较:equals比较忽略大小写:equalsIgnoreCaseindexOf:如果字符串中有传入的assci码对应的值,返回下标 1./** 2.* String && StringBuilder 3.*/ 4.val str "abcd" 5.val s…...

Power Automate-当收到HTTP请求时触发流程
选择创建自动化云端流,点跳过 第一个操作搜索HTTP,点击当收到HTTP请求时 点击使用示例有效负载生成架构 写入JSON,点击完成 正文JSON架构就自动生成了,再点击左下角的显示高级选项 Method根据需求选择 可以选择JSON中的参数赋值给…...

学习c#的第十四天
目录 C# 接口(Interface) 接口的特点 定义接口 接口继承 接口和抽象类的区别 C# 命名空间(Namespace) using 关键字 定义命名空间 嵌套命名空间 C# 接口(Interface) 接口定义了所有类继承接口时应…...

6.jvm中对象创建流程与内存分配
目录 概述对象的创建流程对象的内存分配方式对象怎样才会进入老年代大对象直接进入老年代内存担保 jvc 相关指令查看jdk默认使用的gc查看当前jdk支持的有哪些gc查看指定进程当前正在使用的gc 结束 概述 相关文章在此总结如下: 文章地址jvm基本知识地址jvm类加载系…...

算法--搜索与图
这里写目录标题 主要内容DFS思想 BFS思想 DFS与BFS的比较一级目录二级目录二级目录二级目录 一级目录二级目录二级目录二级目录 一级目录二级目录二级目录二级目录 主要内容 DFS 思想 会优先向深处搜索 一旦到达最深处 那么会回溯 但是在回溯的过程中 会边回溯边观察是否有能继…...
ROS 文件系统
ROS文件系统级指的是在硬盘上ROS源代码的组织形式,ROS 的文件系统本质上都还是操作系统文件,可以使用Linux命令来操作这些文件,文件操作,包含增删改查与执行等操作,ROS文件系统的一些常用命令如下: 1.增加…...

车载通信与DDS标准解读系列(1):DDS-RPC
▎RPC & DDS-RPC RPC:Remote Procedure Call,远程过程调用。 远程过程调用是一种进程间通信,它允许计算机程序在另一个地址空间中执行子程序,就好像用别人的东西像用自己的一样,常用于分布式系统。 远程过程调用…...
通过构造树形结构介绍map的用法
构造TreeSelect树形结构: 当我们拿到的数据与我们要用的数据不一致时,就要改造成自己想要的数据结构。 后端拿到的数据结构: public class TPMGroup{public string DepName { get; set; }public List<staff> TPMList { get; set; }pu…...

代码随想录算法训练营Day 53 || 1143.最长公共子序列、1035.不相交的线、53. 最大子序和
1143.最长公共子序列 力扣题目链接 给定两个字符串 text1 和 text2,返回这两个字符串的最长公共子序列的长度。 一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何…...
Oracle JDBC数据库驱动程序介绍
Maven Central上所有Oracle JDBC数据库驱动程序 现在不仅可以在Maven Central上使用甲骨文数据库最新版本,而且还可以获得所有受支持的Oracle JDBC驱动程序发行版,包括19.3.0.0、18.3.0.0、12.2.0.1和11.2.0.4。从现在开始,Maven Central确实…...

深入剖析AI大模型:大模型时代的 Prompt 工程全解析
今天聊的内容,我认为是AI开发里面非常重要的内容。它在AI开发里无处不在,当你对 AI 助手说 "用李白的风格写一首关于人工智能的诗",或者让翻译模型 "将这段合同翻译成商务日语" 时,输入的这句话就是 Prompt。…...

超短脉冲激光自聚焦效应
前言与目录 强激光引起自聚焦效应机理 超短脉冲激光在脆性材料内部加工时引起的自聚焦效应,这是一种非线性光学现象,主要涉及光学克尔效应和材料的非线性光学特性。 自聚焦效应可以产生局部的强光场,对材料产生非线性响应,可能…...

vscode(仍待补充)
写于2025 6.9 主包将加入vscode这个更权威的圈子 vscode的基本使用 侧边栏 vscode还能连接ssh? debug时使用的launch文件 1.task.json {"tasks": [{"type": "cppbuild","label": "C/C: gcc.exe 生成活动文件"…...

前端导出带有合并单元格的列表
// 导出async function exportExcel(fileName "共识调整.xlsx") {// 所有数据const exportData await getAllMainData();// 表头内容let fitstTitleList [];const secondTitleList [];allColumns.value.forEach(column > {if (!column.children) {fitstTitleL…...

令牌桶 滑动窗口->限流 分布式信号量->限并发的原理 lua脚本分析介绍
文章目录 前言限流限制并发的实际理解限流令牌桶代码实现结果分析令牌桶lua的模拟实现原理总结: 滑动窗口代码实现结果分析lua脚本原理解析 限并发分布式信号量代码实现结果分析lua脚本实现原理 双注解去实现限流 并发结果分析: 实际业务去理解体会统一注…...

《基于Apache Flink的流处理》笔记
思维导图 1-3 章 4-7章 8-11 章 参考资料 源码: https://github.com/streaming-with-flink 博客 https://flink.apache.org/bloghttps://www.ververica.com/blog 聚会及会议 https://flink-forward.orghttps://www.meetup.com/topics/apache-flink https://n…...

QT: `long long` 类型转换为 `QString` 2025.6.5
在 Qt 中,将 long long 类型转换为 QString 可以通过以下两种常用方法实现: 方法 1:使用 QString::number() 直接调用 QString 的静态方法 number(),将数值转换为字符串: long long value 1234567890123456789LL; …...

九天毕昇深度学习平台 | 如何安装库?
pip install 库名 -i https://pypi.tuna.tsinghua.edu.cn/simple --user 举个例子: 报错 ModuleNotFoundError: No module named torch 那么我需要安装 torch pip install torch -i https://pypi.tuna.tsinghua.edu.cn/simple --user pip install 库名&#x…...
C++.OpenGL (14/64)多光源(Multiple Lights)
多光源(Multiple Lights) 多光源渲染技术概览 #mermaid-svg-3L5e5gGn76TNh7Lq {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-3L5e5gGn76TNh7Lq .error-icon{fill:#552222;}#mermaid-svg-3L5e5gGn76TNh7Lq .erro…...
C#中的CLR属性、依赖属性与附加属性
CLR属性的主要特征 封装性: 隐藏字段的实现细节 提供对字段的受控访问 访问控制: 可单独设置get/set访问器的可见性 可创建只读或只写属性 计算属性: 可以在getter中执行计算逻辑 不需要直接对应一个字段 验证逻辑: 可以…...