C. Date(类与对象)

下面是一个日期类的定义,请在类外实现其所有的方法,并在主函数中生成对象测试之。

 注意,在判断明天日期时,要加入跨月、跨年、闰年的判断

例如9.月30日的明天是10月1日,12月31日的明天是第二年的1月1日

2月28日的明天要区分是否闰年,闰年则是2月29日,非闰年则是3月1日

输入

测试数据的组数t

第一组测试数据的年 月 日

..........

要求第一个日期的年月日初始化采用构造函数,第二个日期的年月日初始化采用setDate方法,第三个日期又采用构造函数,第四个日期又采用setDate方法,以此类推。

输出

输出今天的日期

输出明天的日期

输入样例1 

4
2012 1 3
2012 2 28
2012 3 31
2012 4 30


输出样例1

Today is 2012/01/03
Tomorrow is 2012/01/04
Today is 2012/02/28
Tomorrow is 2012/02/29
Today is 2012/03/31
Tomorrow is 2012/04/01
Today is 2012/04/30
Tomorrow is 2012/05/01

#include <iostream>
#include<cstring>
#include<iomanip>
using namespace std;
class Date {
    int year, month ,day;
public:
    Date();
    Date(int y, int m, int d);
    int getYear();
    int getMonth();
    int getDay();
    void setDate(int y, int m, int d);
    void print();
    bool isleapyear();
    void addOneDay();
};
Date::Date() {
    year = 1900;
    month = 1;
    day = 1;
}
Date::Date(int y, int m, int d) :year(y),month(m),day(d){}
int Date::getYear() {
    return year;
}
int Date::getMonth() {
    return month;
}
int Date::getDay() {
    return day;
}
void Date::setDate(int y, int m, int d) {
    year = y;
    month = m; 
    day = d;
}
void Date::print() {
    cout << year << '/' <<  setfill('0') << setw(2) << month << '/' << setfill('0')<<setw(2) << day << endl;

}
bool Date::isleapyear() {
    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
        return true;
    }
    else {
        return false;
    }
}
void Date::addOneDay() {
    int a[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
    if (isleapyear()) {
        a[2]++;
    }
    if (day < a[month]) {
        day++;
    }
    else {
        if (month == 12) {
            day = 1;
            month = 1;
            year++;
        }
        else {
            month++;
            day = 1;
        }
    }
}
int main()
{
    int t;
    int y, m, d;
    cin>>t;
    for (int i = 1; i <= t; i++) {
        cin >> y >> m >> d;
        if (i % 2 == 1) {
            Date date(y, m, d);
            cout << "Today is ";
            date.print();
            date.addOneDay();
            cout << "Tomorrow is ";
            date.print();
        }
        else {
            Date date;
            date.setDate(y, m, d);
            cout << "Today is ";
            date.print();
            date.addOneDay();
            cout << "Tomorrow is ";
            date.print();
        } 
    }
}

实验一的三道题目比较简单,所有没有深究及注释。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值