#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 >> ye AR >> month >> day; return *this; } void Swap (date & RHS) {date T (*this); *this = RHS; RHS = t; }};bool is_leap (int year) {return (year% 400) | | (Year% of 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>//by constantly using one of them to another approximation to find the difference in number of days 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>//two dates are always bounded by each other, so date size relationships cannot change 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;}
C + + to find days between two dates