类实现时间差
Problem A: 1,2,3班_Contest1_Q1
Time Limit: 1 Sec Memory Limit: 128 MB Submit: 517 Solved: 142 [Submit][Status][Web Board]Description
设定一个时间类,类中包含年、月、日,计算任意两个时间之间的天数,并显示出来。注意闰年与平年
类如下:
class Date
{
private:
int year;
int month;
int day;
public:
Date(void);
Date(int year,int month,int day);
~Date(void);
int getDateDiff(Date date2);
};
Input
从键盘上输入两个日期,如2012/02/02、2013/02/03
Output
打印两个日期之间的天数
Sample Input
2013/03/28 2013/04/08
Sample Output
11
HINT
#include<iostream> using namespace std; class Date { int year; int month; int day; bool prime; public: Date(int y,int m,int d):year(y),month(m),day(d){ if((year%4==0&&year%100!=0)||(year%400==0)) prime = true; else prime = false; } Date(Date& it); int getyear(){return year;} int getmonth(){return month;} int getday(){return day;} friend int operator-(Date&date1,Date&date2); Date operator++(); friend bool operator>(Date&date1,Date&date2); }; Date::Date(Date&it){ year = it.year; month = it.month; day = it.day; if((year%4==0 && year%100!=0)||(year%400==0)) prime = true; else prime = false; } Date Date::operator++() { if(day==28) { if(prime) day++; else if(month==2) { day = 1;month++;} else day++; } else if(day==29) { if(month==2) { day = 1;month++;} else day++; } else if(day==30){ if(month==1||month==3||month==5||month==7||month==8||month==10||month==12) day++; else {day=1;month++;} } else if(day==31){ day=1;month++; } else day++; if(month==13) { year++; month=1; if((year%4==0 && year%100!=0)||(year%400==0)) prime = true; else prime = false; } return*this; } bool operator>(Date&date1,Date&date2) { if(date1.getyear()>date2.getyear()) return true; else if(date1.getmonth()>date2.getmonth()) return true; else if(date1.getday()>date2.getday()) return true; else return false; } int operator-(Date&date1,Date&date2){ int sum=0; Date maxdate = date1.getyear() > date2.getyear() ? date1:date2; Date mindate = date1.getyear() <= date2.getyear() ? date1:date2; int y = 0; for( y = mindate.getyear();y<maxdate.getyear()-1;y++) { if((y%4==0&&y%100!=0)||(y%400==0)) sum+=366; else sum+=365; } Date datesome(y,mindate.getmonth(),mindate.getday()); while(1) { if(maxdate > datesome) {sum++;++datesome;} else break; } return sum; } int main(){ int year,month,day; cin>>year; getchar(); cin>>month; getchar(); cin>>day; Date date01(year,month,day); cin>>year; getchar(); cin>>month; getchar(); cin>>day; Date date02(year,month,day); int sum = date01 - date02; cout<<sum<<endl; }