声明类Date
要求:
1、使用户可以设置日期,并在输入错误时提示。
a一年12个月,若输入12以外的数,提示“输入月份错误”
b每个月依次有{31,28/29,31,30,31,30,31,31,30,31,30,31}若输入的数值超过该月天数,提示“输入天数错误”。
2、可以查询两个日期之间相差天数
注意:闰年
Code
#include <iostream>
using namespace std;
#include<time.h>
class Date
{ public:
Date(int,int,int);
int Leapyear(int);
double days();
private:
int day,month,year;
};
void main()
{ int day,month,year;
cout<<"请您输入年、月、日 ";
cin>>year>>month>>day;
Date date(day,month,year);
cout<<date.days()<<endl;
}
Date::Date(int day, int month, int year)
{ if (year<0)
{ cout<<"您所输入的年份不在本程序计算范围之内!"<<endl;
return ;
}
if(month>12||month<1)
{ cout<<"您输入的月份有误 "<<endl;
return;
}
if((month==1||month==3||month==5||month==7||month==8||month==10||month==12))
{ if(day<1||day>31)
{ cout<<"您输入的天数有误,"<<endl;
return;
}
}
if(month==4||month==6||month==9||month==11)
{ if(day<1||day>30)
{ cout<<"您输入的天数有误,"<<endl;
return;
}
}
if(month==2&&(Leapyear(year)))
{ if(day<1||day>29)
{ cout<<"您输入的天数有误,"<<endl;
return;
}
}
if(month==2&&(!Leapyear(year)))
{ if(day<1||day>28)
{ cout<<"您输入的天数有误,"<<endl;
return;
}
}
this->day=day;
this->month=month;
this->year=year;
cout<<"公元"<<year<<"年"<<month<<"月"<<day<<"日"<<endl;
}
inline double Date:: days()
{ struct tm time1,time2;
int year;
int month;
cout<<"请输入年月日\n";
cout<<"年:";
cin>>year;
time1.tm_year=year-1900;
cout<<"月:";
cin>>month;
time1.tm_mon=month+1;
cout<<"日:";
cin>>time1.tm_mday;
time1.tm_hour=0;
time1.tm_min=0;
time1.tm_sec=0;
cout<<"----------------"<<endl;
cout<<"年:";
cin>>year;
time2.tm_year=year-1900;
cout<<"月:";
cin>>month;
time2.tm_mon=month+1;
cout<<"日:";
cin>>time2.tm_mday;
cout<<"相差天数为:";
time2.tm_hour=0;
time2.tm_min=0;
time2.tm_sec=0;
return (mktime(&time2)-mktime(&time1))/(24*60*60.0);
}
inline int Date::Leapyear(int year)
{ if(((year%4==0)&&(year%100!=0))||(year%400==0))
return true;
else return false;
}