C++作业-输出日期

任务描述:

定义一个满足如下要求的Date类(数据成员为int变量日,月,年,设置为私有的)。

    1. 输入日期,设置日期并判断日期的合法性。
    1. 用下面的格式输出日期:
      日/月/年
    1. 可运行在合法日期上加一天操作;

1) 将类的定义(只放成员函数声明)放在Date.h中,将代码贴在下方空白处


```cpp
#include<iostream>
using namespace std;
class Date {
public:
	void Set(int m, int d, int y);   // 传入 时间
	int dayMonth(int month);         // 计算某个月的天数
	int Judge_date();				// 判断日期是否合法
	void Print();					// 打印当前日期
	void Nextday();					// 打印明天日期
private :
	int day, month, year;
};

2. 将成员函数的实现放在Date.cpp中,将代码贴在下方空白处

#include "date.h"
void Date::Set(int d, int m, int y) {    //置日期值
    month = m; day = d; year = y;
}

// 计算某个月份的天数
int Date::dayMonth(int month) {
    if (month == 4 || month == 5 || month == 7 || month == 9 || month == 11) {
        return 30;
    }
    else if (month == 2) // 如果是2月 分 闰年、非闰年讨论
    {
        if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
        {
            return 29;    // 闰年 29 天
        }
        else
            return 28;    // 非 闰年 29 天
    }
    else {
        return 31;         // 1、2、3、6、8、10、12 返回31天
    }
}
int  Date::Judge_date() {               //判日期是否合法
    if (year >= 1 && (month > 0 || month < 13)) {   // 判断年和月合法之后,我们来判断日与月是否合法
        int Emonth_day = dayMonth(month);
        if (day<1 || day > Emonth_day) {
            cout << "日期有误!";
            return 0; // 有误返回0
        }
        else
            return 1;
    }
}




void Date::Print() {                   //输出日期值
    cout << "当前日期为:" << day << "/" << month << "/" << year << endl;

}


void Date::Nextday() {
    //if (month == 12 && day == 31) 
    //{ year++; 
    //month = 1;
    //}
    day++;
    if (day > dayMonth(month))              // 如果大于当前日期的月,则指向下一个月的第一天(因为输出的是明天)
    {
        if (month == 12) {
            year++;
            month = 1;     // 如果比12天的最大天数还大,则跳转下月
        }
        else
            month++;
        day = 1;
    }
    cout << "明天日期为:" << day << "/" << month << "/" << year << endl;
}

3.将main函数放在App.cpp中,将代码贴在下方空白处,并用以下测试用例测试,将测试结果贴在下方空白处。




```cpp
#include<iostream>
#include"date.h"
using namespace std;
//---------------------




int main() {
    Date time_1;
    int day, month, year;
    cout << "请输入日期(日 月 年)" << endl ;
    cin >> day >> month >> year;    // 输入时间
    time_1.Set(day, month, year);  // 通过调用类函数传入私有数据
    if (time_1.Judge_date() == 1)  // 如果返回1则输出 否则返回0说明日期有误不输出
    {
        time_1.Print();
        time_1.Nextday();
    }
       
    //  a.month;     //错误!month是私有成员,不能通过对象访问
}//--------------------


在这里插入图片描述

  • 3
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值