PTA 7-9 编写一个友元函数,求两个日期之间相差的天数。

题目

设计一个日期类Date,包括日期的年份、月份和日号,编写一个友元函数,求两个日期之间相差的天数。该类中设计有3个友元函数;count_day()函数,它有两个参数,第2个参数是一个标志,当其值等于1 时,计算一年的开始到某日期的天数;否则计算某日期到年尾的天数。leap()函数用于判断指定的年份是否为闰年。subs()函数用于计算两个日期之间的天数。 当时间输入不正确时,输出“time error!”

输入样例:

在这里给出一组输入。例如:

2000 1 1 
2002 10 1

输出样例:

在这里给出相应的输出。例如:

1004

代码:

//7-9 编写一个友元函数,求两个日期之间相差的天数
#include<iostream>
using namespace std;
int is_leap(const int &year);
class Date
{
private:
    int year, month, day;

public:
    Date(int y = 0, int m = 1, int d = 1) : year(y), month(m), day(d) { ; }
    friend int is_leap(const int &year);
    friend int count_day(const Date &d, int flag);
    friend int subs(const Date &d1, const Date &d2);
    friend bool operator>=(const Date &d1, const Date &d2);

    int is_big_month()
    {
        int dm[7] = {1, 3, 5, 7, 8, 10, 12};
        for (int i = 0; i < 7; i++) if (dm[i] == month) return 1;
        return 0;
    }
    bool is_legal()
    {
        if (year > 0 && month <= 12 && month >= 1 && day >= 1)
        {
            if (month == 2 && day <= 28 + is_leap(year)) return true;
            else if (month != 2 && day <= 30 + is_big_month()) return true;
        }
        return false;
    }
};

bool operator>=(const Date &d1, const Date &d2)
{
    if (d1.year<d2.year)return false;
    if (d1.month<d2.month)return false;
    if (d1.day<d2.day)return false;
    return true;
}


int is_leap(const int &year)
{
    if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) return 1;
	else return 0;
}

int count_day(const Date &d, int flag)
{
    int ans, isleap = is_leap(d.year);
    ans = 31 * (d.month - 1) + d.day;
    if (d.month > 2)
    {
        ans -= (4 * (d.month) + 23) / 10;
        ans += isleap;
    }
    if (flag == 1) return ans;
    return 365 + isleap - ans;
}

int subs(const Date &d1, const Date &d2)
{
    if (d1.year == d2.year) return count_day(d2, 1) - count_day(d1, 1);
    int ans = 0;
    for (int i = d1.year + 1; i < d2.year; i++) ans += 365 + is_leap(i);
    ans += count_day(d2, 1);
    ans += count_day(d1, 2);
    return ans;
}


int main()
{

        int y, m, d;
        cin >> y >> m >> d; Date d1(y, m, d);
        cin >> y >> m >> d; Date d2(y, m, d);
        if (d1.is_legal() && d2.is_legal() && d2>=d1) cout << subs(d1, d2);
        else cout << "time error!";
 
    return 0;
}

吐槽:

傻逼wx题目不写清楚点。

第二个时间需要大于第一个。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值