C++ 求两日期间相隔天数
发布时间:2020-12-16 07:45:47 所属栏目:百科 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 #include iostream #include algorithm #include cmath using namespace std; struct Date{ int year; int month; int day; Date(int y = 0,int m = 0
以下代码由PHP站长网 52php.cn收集自互联网 现在PHP站长网小编把它分享给大家,仅供参考 #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; } 以上内容由PHP站长网【52php.cn】收集整理供大家参考研究 如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |