日期类----北京理工大学机试题

这题我采用的方法是:

如果是一年的最后一天,则直接year++   month=1  day=1

其他情况则:

根据月份和天数计算出这是本年的第几天,然后加一

然后根据天数计算日期。算是之前两种方法的合并。但是比较好理解。

#include <bits/stdc++.h>
using namespace std;
#define N 100
class Date
{
private:
    int year=0;
    int month=0;
    int day=0;

public:
    void addDate();
    Date(int a, int b, int c);
    Date();
};

Date::Date(int a, int b, int c)
{
    year = a;
    month = b;
    day = c;
}

Date::Date()
{
    int year=0;
    int month=0;
    int day=0;
}

void Date::addDate()
{
    if(month==12 && day==31)
    {
        year = year+1;
        month = 1;
        day = 1;
    }
    else
    {
        //由于是没有闰年测试,则二月为28
        int dayarr[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        int sum=0; //月中的日期累计
        for(int i=1;i<=month-1;i++)
        {
            sum+=dayarr[i];
        }
        sum = sum+day+1;//实现加一
        // 根据天数反向求日期
        int sum_monthday = 0; //累计天数
        int month_real = 0;//对应的月份
        for(int i=1;i<=12;i++)
        {
            sum_monthday+=dayarr[i];
            if(sum_monthday>=sum) //当累计天数大于实际天数 跳出
            {
                month_real = i;
                break;
            }
        }
        month = month_real;
        //用sum减去当月之前的所有月份天数==当月的天数
        //当月之前的所有天数=累计天数-本月天数
        day = sum-(sum_monthday-dayarr[month]);
    }
    printf("%d-%02d-%02d\n", year, month, day);
}


int main()
{
    int n = 0;
    scanf("%d", &n);
    Date D[N];
    for(int i=0; i<n; i++)
    {
        int a=0,b=0,c=0;
        scanf("%d %d %d", &a, &b, &c);
        D[i]=Date(a,b,c);
    }
    for(int i=0; i<n; i++)
    {
        D[i].addDate();
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值