C++ 求两日期间相隔天数
来源:互联网 发布:300451创业软件股吧 编辑:程序博客网 时间:2024/05/16 11:25
#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;}
0 0
- C++ 求两日期间相隔天数
- 两个日期间相隔的天数--zzuli1654
- 求解任意两日期间相隔的天数
- jqueryeasyui 中 datetimebox 取两个日期间相隔的天数
- 相隔天数
- c#(asp.net) 如何计算两个日期之间相隔天数
- c实现任给两日期计算相隔天数问题
- C/C++完成两个日期之间相隔天数的计算
- 简单计算相隔天数
- 计算日期相隔天数
- php相隔算天数
- 2日期相隔天数
- 日期问题:相隔天数
- js 计算日期相隔天数
- C#计算日期相隔天数
- java编程,计算相隔天数
- 计算两个日期相隔天数
- 计算两个日期相隔天数
- 关于如何修改weblogic用户密码的问题
- ps的路径使用
- HDU_5249(百度之星D题)
- 搭建OpenWrt开发环境(包括编译过程)
- 产生冠军set容器
- C++ 求两日期间相隔天数
- [Emacs学习笔记]保存文件和相关操作
- 初学Java—心得体会
- SQL Server 开发指南---Transact-SQL 编程
- 位操作
- 图片上传之fileupload
- 解决ThinkPad S3-440无法睡眠问题
- 下载代码整理
- Flask Ajax Demo