日期处理
日期处理每次思考时都会感觉很麻烦,因为我们必须处理好平年与闰年,大月与小月等细节的关系。我们列出解决该类问题的一个思路。
问题:
有两个日期,求这两个日期之间的天数。
样例输入:
20181225
20181226
样例输出:
1
思路:可以令较小的日期不断加一天直到等于较大的日期,利用Count计数即可。并且我们可以给定一个二维数组int month[13][2]存放每个月的天数,第二维0表示平年,1表示闰年。当然如果感觉这样太麻烦直接将较小日期的年份加到比较大年份小1即可,中间计算多少个平年与闰年
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<cstring>
using namespace std;
int month[13][2]=
{
{0,0},{31,31},{28,29},{31,31},{30,30},{31,31},{30,30},{31,31},{31,31},{30,30},{31,31},{30,30},{31,31}
};//平年和闰年的每个月的天数
bool YN(int year)//判读是否为闰年
{
return (year%4==0&&year%100!=0)||(year%400==0);
}
int main()
{
int t1,t2;
cin>>t1>>t2;
if(t1>t2)
swap(t1,t2);
int y1,m1,d1;
int y2,m2,d2;
y1=t1/10000,m1=t1%10000/100,d1=t1%100;
y2=t2/10000,m2=t2%10000/100,d2=t2%100;
int ans=1;
while(y1<y2||m1<m2||d1<d2)
{
d1++;
if(d1==month[m1][YN(d1)]+1)
{
m1++;
d1=1;
}
if(m1==13)
{
y1++;
m1=1;
}
ans++;
}
cout<<ans;
return 0;
}