杂题,目前正在学习C++,学习过程中碰到的题目。贴出来。
给出两个年月日 求出天数差。
如果从一月份算到十二月份,由于闰年和平年二月的天数不同,计算过程会有点麻烦,因此作如下转换。
将三月初到下一年的二月底看作一个完整的一年 ,如图所示。
将元年作为参照物,不用考虑元年的一二月,天数相同,因此求差值的时候不会有影响。
代码如下:
- #include <iostream>
- using namespace std;
- class Date
- {
- private:
- int D_year;
- int D_month;
- int D_day;
- public:
- Date(int y, int m, int d)
- {
- D_year = y;
- D_month = m;
- D_day = d;
- }
- int FromThatDay() const
- {<span style="white-space:pre"> //计算出输入的年月日距离元年3.1的天数</span>
- int day = (D_year - 1) * 365 + D_year / 4 + D_year / 400 - D_year / 100;
- const int month[] = { 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28 };
- if (D_month >= 3)
- {
- for (int i = 0; i < D_month - 3; i++)
- day += month[i];
- day += D_day;
- }
- else
- {
- int isLeapYear = 0;
- if (D_year % 4 == 0 || D_year % 400 == 0)
- isLeapYear = 1;
- day -= 31 + 28 + isLeapYear;
- if (D_month == 2)
- day += 31;
- day += D_day;
- }
- return day;
- }
- static int FromThatDay(const Date& obj1, const Date& obj2)
- {
- return obj1.FromThatDay() - obj2.FromThatDay();
- }
- };
- int main()
- {
- Date t1(2000, 1, 3);
- Date t2(2000, 3, 9);
- cout << Date::FromThatDay(t2, t1) << endl;
- }