蓝桥杯训练 日期训练

这道题做起来还是有些麻烦的,做了一个小时多点,码力不行呀。。。

思路:

首先输入a的年月日,b存储2011,11,11,交换两个日期变量,让日期a 存储较小的日期,日期b存储较大的。

 我们需要计算出两个日期之间相差多少天,我想的是计算 a日期所在年过去了多少天sum1,再计算b日期所在年还有多天没过sum2,最后用a的年份到b的年份的总天数-(sum1+sum2),得到两个日期差了多少天。

最后还得分类一下两个日期是否交换过,有无交换过处理不同。。注释有。。

代码

#include <iostream>
#include <malloc.h>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
typedef long long LL;
const int maxn = 1000 + 10;
const int inf = 0x3f3f3f3f;
int c[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
struct Data
{
    int year, month, day;
};
bool check(int n)
{
    if ((n % 100 != 0 && n % 4 == 0) || (n % 100 == 0 && n % 400 == 0))
        return true;
    return false;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
#endif
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    // 已知 2011 年 11 月 11 日是星期五
    Data a; // a 留小的
    Data b; // b 留大日子
    int flag = 0;
    int ans;
    b.year = 2011;
    b.month = 11;
    b.day = 11;
    cin >> a.year >> a.month >> a.day;
    if ((a.year > b.year) || (a.year == b.year && a.month > b.month) || (a.year == b.year && a.month == b.month && a.day > b.day))
    {
        swap(a, b);
        flag = 1;
    }
    // cout << a.year << " " << a.month << " " << a.day << endl;
    // cout << b.year << " " << b.month << " " << b.day << endl;
    int sum = 0;
    for (int i = 1; i < a.month; i++)
    {
        sum += c[i];
        if (i == 2 && check(a.year))
            sum++;
    }
    sum += a.day;
    for (int i = b.month; i <= 12; i++)
    {
        sum += c[i];
        if (i == 2 && check(b.year))
            sum++;
    }
    sum -= b.day;
    int all = 0;
    for (int i = a.year; i <= b.year; i++)
    {
        all += 365;
        if (check(i))
            all++;
    }
    all -= sum;
    if (flag == 0) // 如果没交换过说明 给定日期比2011 11 11 日期早
    {              //不能向前找,还是得向后找,具体处理如 73 74 行
        all = all % 7;
        ans = (5 + (7 - all)) % 7;
        if (ans == 0)
            cout << 7;
        else
            cout << ans;
    }
    else
    {
        ans = (5 + all) % 7;
        if (ans == 0)
            cout << 7;
        else
            cout << ans;
    }
    return 0;
}
发布了64 篇原创文章 · 获赞 24 · 访问量 7904

猜你喜欢

转载自blog.csdn.net/qq_44115065/article/details/104159273
今日推荐