【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 处理多个 case
        cin >> 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);
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/142334.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

027 - STM32学习笔记 - ADC初识(一)

026- STM32学习笔记 - ADC初识&#xff08;一&#xff09; 前几天不小心把板子掉地上了&#xff0c;液晶屏摔坏了&#xff0c;暂时先停一下液晶屏的学习&#xff0c;等新的板子来了再继续学习。 一、ADC介绍 ADC指的是Analog to Digital Converter&#xff08;模数转换器&…

​2005/2008-2022逐年道路网分布数据

道路网&#xff08;road network&#xff09;指的是在一定区域内&#xff0c;由各种道路组成的相互联络、交织成网状分布的道路系统。全部由各级公路组成的称公路网。在城市范围内由各种道路组成的称城市道路网。 城市道路网由城镇管辖范围内的各种不同功能的干道和区域…

vmware 修改主机名称 hadoop 服务器环境配置(一)

如何在虚拟机配置主机名称&#xff1a; 1. 如图所示在/etc 文件夹下有个hosts文件。追加映射关系&#xff1a; #关系 ip地址 名称 192.168.164.20 hadoop20 2. 保存后&#xff0c;重启reboot即可

GoldWave 6.78中文免费激活版功能特色2024最新功能解析

GoldWave 6.78中文免费激活版是一款多功能、强大且用户友好的音频编辑工具。它为音乐制作人、播客主持人以及音频编辑爱好者提供了全面的编辑功能&#xff0c;让你能够创造出高质量的音频作品。无论你是在音乐制作、音频修复还是播客制作&#xff0c;GoldWave 都是一个值得一试…

第1关:构造函数与析构函数的实现

题目&#xff1a;根据.h写出.cpp 考点&#xff1a; 1.链表的默认构造&#xff0c; 拷贝构造&#xff0c;传参构造以及析构函数等。 代码&#xff1a; /********** BEGIN **********/ #include <cstdlib> #include <cstring> #include "LinkedList.h&…

卷积神经网络(1)

目录 卷积 1 自定义二维卷积算子 2 自定义带步长和零填充的二维卷积算子 3 实现图像边缘检测 4 自定义卷积层算子和汇聚层算子 4.1 卷积算子 4.2 汇聚层算子 5 学习torch.nn.Conv2d()、torch.nn.MaxPool2d()&#xff1b;torch.nn.avg_pool2d()&#xff0c;简要介绍使用方…

服务器常见问题排查(一)—cpu占用高、上下文频繁切换、频繁GC

一般而言cpu异常往往还是比较好定位的。原因包括业务逻辑问题(死循环)、频繁gc以及上下文切换过多。而最常见的往往是业务逻辑(或者框架逻辑)导致的&#xff0c;可以使用jstack来分析对应的堆栈情况。 使用jstack排查占用率问题 当使用jstack排查占用率问题时&#xff0c;可以…

如何下载全国水系、铁路、土地、交通设施和运输相关数据?

​ 通过以下方法可以将全国水系、铁路、土地、交通设施和运输相关数据下载到本机。 方法/步骤 下载GIS地图下载器 http://www.geosaas.com/download/mapdownloader.exe&#xff0c;安装完成后桌面上出现”GIS地图下载器“图标。 2、双击桌面图标打开”GI…

11-13 spring整合web

spring注解 把properties文件中的key注入到属性当中去 xml配置文件拆分 -> import标签 注解开发中 import 实现 搞一个主配置类&#xff0c;其他配置类全部导入进来这个这个主配置类 而且其他配置类不需要 加上configuration注解 之前这个注解用于表示这是一个配置文件 …

【论文精读】Pose-Free Neural Radiance Fields via Implicit Pose Regularization

今天读的是一篇发表在ICCV 2023上的文章&#xff0c;作者来自NTU。 文章地址&#xff1a;点击前往 文章目录 Abstract1 Intro2 Related Work3 Preliminary4 Proposed Method4.1 Overall Framework4.2 Scene Codebook Construction4.3 Pose-Guided View Reconstruction4.4 Train…

Windows 微PE WePE_64_V2.3 PE模式下启用账号和修改密码

启动PE后&#xff0c;进入桌面打开运行dism程序 选择带有系统的盘符&#xff08;默认选的是PE盘&#xff09;&#xff0c;然后打开会话 选择左侧工具箱&#xff0c;然后右侧找到账户管理 然后就可以对已有账号进行管理了 结束。

【python自动化】Playwright基础教程(四)事件操作①高亮元素匹配器鼠标悬停

本文目录 文章目录 前言高亮显示元素定位 - highlighthighlight实战highlight定位多个元素 元素匹配器 - nthnth实战演示 元素匹配 - first&last 综合定位方式时间操作进行实战&#xff0c;巩固之前我们学习的定位方式。 这一部分内容对应官网 : https://playwright.dev/py…

Java SE 封装、包、static关键字和代码块

1.封装 1.1封装的概念 面向对象程序三大特性&#xff1a;封装、继承、多态。而类和对象阶段&#xff0c;主要研究的就是封装特性。何为封装呢&#xff1f;简单来说 就是套壳屏蔽细节。 封装&#xff1a;将数据和操作数据的方法进行有机结合&#xff0c;隐藏对象的属性和实现细…

关于反弹Shell个人的一些理解与学习收获

反弹Shell 概念&#xff1a; 反弹shell(reverse shell)&#xff0c;就是控制端(攻击者所有)监听某TCP/UDP端口&#xff0c;被控端发起请求到该端口&#xff0c;并将其命令行的输入输出转发到控制端。reverse shell与telnet&#xff0c;ssh等标准shell对应&#xff0c;本质上是…

C++模拟实现——AVL树

AVL树 1.介绍 AVL树是对搜索二叉树的改进&#xff0c;通过特定的方法使得每个节点的左右子树高度差绝对值不超过1&#xff0c;使得避免出现歪脖子的情况&#xff0c;最核心的实现在于插入值部分是如何去实现平衡调整的&#xff0c;由于前面详细实现和解析过搜索二叉树&#x…

Android问题笔记四十四:关于RecyclerView出现Inconsistency detected崩溃

点击跳转>Unity3D特效百例点击跳转>案例项目实战源码点击跳转>游戏脚本-辅助自动化点击跳转>Android控件全解手册点击跳转>Scratch编程案例点击跳转>软考全系列 &#x1f449;关于作者 专注于Android/Unity和各种游戏开发技巧&#xff0c;以及各种资源分享&…

Linux---(六)自动化构建工具 make/Makefile

文章目录 一、make/Makefile二、快速查看&#xff08;1&#xff09;建立Makefile文件&#xff08;2&#xff09;编辑Makefile文件&#xff08;3&#xff09;解释&#xff08;4&#xff09;效果展示 三、背后的基本知识、原理&#xff08;1&#xff09;如何清理对应的临时文件呢…

vite 深入浅出

vite 深入浅出 简介 vite(轻量&#xff0c;轻快的意思) 是一个由原生 ES Module 驱动的 Web 开发前端构建工具。 浏览器原生 ESM&#xff1a;浏览器支持的 JavaScript 模块化标准&#xff0c;可以直接使用 <script type"module"> 标签加载模块&#xff0c;无…

第二证券:定增价公布后第二天股价表现?

近年来&#xff0c;定增成为一种较为老练的公司融资方法&#xff0c;它通过向指定政策定向发行股份来筹集资金&#xff0c;相关于非公开发行股票或增发股份&#xff0c;定增的市场轰动和价格变化相对较小。但是&#xff0c;定增股票发行通常会推动股价的不坚决和出资者的心境崎…

Prometheus+Ansible+Consul实现服务发现

一、简介 1、Consul简介 Consul 是基于 GO 语言开发的开源工具&#xff0c;主要面向分布式&#xff0c;服务化的系统提供服务注册、服务发现和配置管理的功能。Consul 提供服务注册/发现、健康检查、Key/Value存储、多数据中心和分布式一致性保证等功能。 在没有使用 consul 服…
最新文章