C++ 求兩日期間相隔天數

cey6 9年前發布 | 700 次閱讀 C/C++

    #include <iostream>

#include <algorithm>  
#include <cmath>  

using namespace std;  

struct Date{  
    int year;  
    int month;  
    int day;  

    Date(int y = 0, int m = 0, int d = 0):  
        year(y), month(m), day(d) {}  

    Date & readIn() {  
        cin >> year >> month >> day;  
        return *this;  
    }  

    void swap(Date & rhs) {  
        Date t(*this);  
        *this = rhs;  
        rhs = t;  
    }  

};  

bool is_leap(int year) {  
    return (year % 400)|| (year % 4 && year % 100);  
}  

bool operator < (const Date & lhs, const Date & rhs) {  
    return (lhs.year < rhs.year) ||  
            (lhs.year == rhs.year) && (lhs.month < rhs.month) ||  
            (lhs.year == rhs.year) && (lhs.month == rhs.month && lhs.day < rhs.day);  
}  

int days_of_month(int year,int month) {  
    switch(month) {  
    case 1: case 3: case 5:case 7:  
    case 8: case 10: case 12:  
        return 31;  
    case 2:  
        return is_leap(year) ? 29: 28;  

    case 4: case 6: case 9: case 11:  
        return 30;  
    default:  
        return -1;  
    }  
}  

int day_diff(Date lhs, Date rhs) {  
<span style="white-space:pre">    </span>//通過不斷用其中一個向另一個逼近來求相差天數  
    int flag = 1;  
    if(rhs < lhs) {  
        swap(lhs, rhs);  
        flag = -1;  
    }  

    int day_shf = 0;  
    if(lhs.day < rhs.day) {  
        day_shf += rhs.day - lhs.day;  
        rhs.day = lhs.day;  
    }  
    if(lhs.day > rhs.day) {  
        day_shf -= lhs.day - rhs.day;  
        lhs.day = rhs.day;  
    }  

    while(lhs.month < rhs.month) {  
        day_shf += days_of_month(lhs.year ,lhs.month);  
        ++lhs.month;  
    }  
    while(lhs.month > rhs.month) {  
        day_shf -= days_of_month(rhs.year ,rhs.month);  
        ++rhs.month;  
    }  
<span style="white-space:pre">    </span>//兩個日期始終以相互為界,故日期大小關系不可能改變  
    while(lhs.year < rhs.year) {  
        day_shf += is_leap(lhs.year) ? 366: 365;  
        ++lhs.year;  
    }  

    return day_shf*flag;  
}  


int main()  
{  
    Date d1, d2;  
    while(true) {  
        d1.readIn(); d2.readIn();  
        cout << day_diff(d1, d2) << endl;  
    }  
    return 0;  
}  </pre> 


 本文由用戶 cey6 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!