zoukankan      html  css  js  c++  java
  • 计算两个日期之间相隔的天数

    Q:给出两个日期,计算出两个日期相隔多少天。

    • 按闭区间来算,即,输出值大于等于2。
    • 难点主要在处理闰年,因为闰年关系到2月份究竟有几天。
    // C++11代码
    #include <iostream>
    #include <cstdio>
    #include <cmath>
    #include <cstring>
    #include <string>
    #include <algorithm>
    #include <vector>
    using namespace std;
    const int N = 110;
    
    int month[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    
    // 闰年需要改2月天数
    void SetLeapYear(int year)
    {
        if (year%100==0 && year%400==0) month[2] = 29;
        if (year%100==0 && year%400!=0) month[2] = 28;
        if (year%100!=0 && year%4==0)   month[2] = 29;
        if (year%100!=0 && year%4!=0)   month[2] = 28;
    }
    
    int main()
    {
        freopen("input.txt", "r", stdin);
        
        string date1, date2;
        while(cin>>date1>>date2)
        {
            int year1 = stoi(date1.substr(0, 4));
            int month1 = stoi(date1.substr(4, 2));
            int day1 = stoi(date1.substr(6, 2));
    
            int year2 = stoi(date2.substr(0, 4));
            int month2 = stoi(date2.substr(4, 2));
            int day2 = stoi(date2.substr(6, 2));
    
            // 相隔的年份[year1, year2) 左开右闭。这样就算多了year1中的部分月,算少了year2中的部分月
            int days = 0;
            for (int i=year1; i<year2; i++)
            {
                SetLeapYear(i);
                for (int j=1; j<13; j++)
                    days += month[j];
            }
    
            // 补上year2算少的部分
            SetLeapYear(year2);
            for (int j=1; j<month2; j++)
                days += month[j];
            days += day2;
    
            // 扣去year1多算的部分
            SetLeapYear(year1);
            for (int j=1; j<month1; j++)
                days -= month[j];
            days -= day1 - 1;
    
            printf("%d
    ", days);
        }
        return 0;
    }
    
  • 相关阅读:
    hadoop再次集群搭建(3)-如何选择相应的hadoop版本
    48. Rotate Image
    352. Data Stream as Disjoint Interval
    163. Missing Ranges
    228. Summary Ranges
    147. Insertion Sort List
    324. Wiggle Sort II
    215. Kth Largest Element in an Array
    快速排序
    280. Wiggle Sort
  • 原文地址:https://www.cnblogs.com/xcw0754/p/8177901.html
Copyright © 2011-2022 走看看