c++:日历的实现

             这次日期类的实现呢,主要具备查某月的日历,日期加减天数后是哪一天,两个日期之间相差的天数。比如说:你想知道离开学的日子还有多少天啊,离我们找工作还有多少天呐,这个月的日历是什么样的啊都可以它来查询!

下面给出代码实现:

Date.h

#ifndef _DATE__H_
#define _DATE__H_
#include<cstdio>
#include<iostream>
using namespace std;
class Date
{
 friend void PrintDate(int year,int month);
public:
 Date(int year,int month,int day);
 Date(const Date& d);
      
 bool JudgeLeapyear(int year)const;
 int SetDay(const Date& d);       //设置每月的天数并返回是哪个月
 Date operator+(int day);        //日期加天数
 Date operator-(int day);       //日期减天数
 int operator-(const Date& date);   //日期减日期(相差天数)
 int Week(int year,int month);     //计算当前月的第一天是星期几
 void Display();
 bool operator==(const Date& d);
 bool operator&g
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 C++ 程序,用于实现日历功能。程序可以根据用户输入的年份和月份,输出该月份的日历。 ```cpp #include<iostream> using namespace std; class Calendar { private: int year; int month; int day; int daysInMonth(); int dayOfWeek(int y, int m, int d); public: Calendar(int y, int m, int d) { year = y; month = m; day = d; } void printCalendar(); }; int Calendar::daysInMonth() { if (month == 2) { if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { return 29; } else { return 28; } } else if (month == 4 || month == 6 || month == 9 || month == 11) { return 30; } else { return 31; } } int Calendar::dayOfWeek(int y, int m, int d) { if (m == 1 || m == 2) { m += 12; y--; } int c = y / 100; y = y % 100; int w = (y + y / 4 + c / 4 - 2 * c + 13 * (m + 1) / 5 + d - 1) % 7; return (w + 7) % 7; } void Calendar::printCalendar() { // 打印标题 cout << "==========================" << endl; cout << " " << year << "年" << month << "月" << endl; cout << "==========================" << endl; cout << " 日 一 二 三 四 五 六" << endl; // 计算该月份的天数和第一天是星期几 int days = daysInMonth(); int firstDayOfWeek = dayOfWeek(year, month, 1); // 打印日历表格 for (int i = 0; i < firstDayOfWeek; i++) { cout << " "; } for (int i = 1; i <= days; i++) { printf("%3d", i); if ((firstDayOfWeek + i - 1) % 7 == 6) { cout << endl; } } if ((firstDayOfWeek + days - 1) % 7 != 6) { cout << endl; } } int main() { int year, month, day; cout << "请输入年份:"; cin >> year; cout << "请输入月份:"; cin >> month; day = 1; // 默认从第一天开始 Calendar calendar(year, month, day); calendar.printCalendar(); return 0; } ``` 运行程序后,用户需要输入年份和月份,程序会输出该月份的日历。例如,输入 2022 年 1 月,程序会输出下面的日历: ``` ========================== 2022年1月 ========================== 日 一 二 三 四 五 六 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ``` 该程序使用了一个 `Calendar` 类来实现日历功能。在这个类中,有两个私有函数 `daysInMonth` 和 `dayOfWeek`,分别用于计算指定月份的天数和该月份第一天是星期几。`printCalendar` 函数用于打印日历表格,首先打印标题,然后计算该月份的天数和第一天是星期几,最后打印日历表格。 这个程序只是一个简单的实现,可以根据需要进行修改和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值