给出两个年月日,计算出天数差。

杂题,目前正在学习C++,学习过程中碰到的题目。贴出来。


给出两个年月日 求出天数差。


如果从一月份算到十二月份,由于闰年和平年二月的天数不同,计算过程会有点麻烦,因此作如下转换。
将三月初到下一年的二月底看作一个完整的一年 ,如图所示。

将元年作为参照物,不用考虑元年的一二月,天数相同,因此求差值的时候不会有影响。

代码如下:
[cpp]  view plain copy
  1. #include <iostream>  
  2. using namespace std;  
  3. class Date  
  4. {  
  5. private:  
  6.     int D_year;  
  7.     int D_month;  
  8.     int D_day;  
  9. public:  
  10.     Date(int y, int m, int d)  
  11.     {  
  12.         D_year = y;  
  13.         D_month = m;  
  14.         D_day = d;  
  15.     }  
  16.   
  17.     int FromThatDay() const  
  18.     {<span style="white-space:pre">           //计算出输入的年月日距离元年3.1的天数</span>  
  19.         int day = (D_year - 1) * 365 + D_year / 4 + D_year / 400 - D_year / 100;  
  20.         const int month[] = { 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28 };  
  21.         if (D_month >= 3)  
  22.         {  
  23.             for (int i = 0; i < D_month - 3; i++)  
  24.                 day += month[i];  
  25.             day += D_day;  
  26.         }  
  27.         else  
  28.         {  
  29.             int isLeapYear = 0;  
  30.             if (D_year % 4 == 0 || D_year % 400 == 0)  
  31.                 isLeapYear = 1;  
  32.             day -= 31 + 28 + isLeapYear;  
  33.             if (D_month == 2)  
  34.                 day += 31;  
  35.             day += D_day;  
  36.         }  
  37.         return day;  
  38.     }  
  39.   
  40.     static int FromThatDay(const Date& obj1, const Date& obj2)  
  41.     {  
  42.         return obj1.FromThatDay() - obj2.FromThatDay();  
  43.     }  
  44. };  
  45.   
  46. int main()  
  47. {  
  48.     Date t1(2000, 1, 3);  
  49.     Date t2(2000, 3, 9);  
  50.     cout << Date::FromThatDay(t2, t1) << endl;  
  51. }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值