#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 > </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 > </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; }
@H_403_0@以上是内存溢出(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。@H_403_0@ 如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。 总结
以上是内存溢出为你收集整理的C++ 求两日期间相隔天数全部内容,希望文章能够帮你解决C++ 求两日期间相隔天数所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)