我不知道自己怎么抽了,代码写了这么长,我正在寻找简洁的算法。。。。。。那些英文的注释和输出提示,是因为我懒得换输入法
#include<iostream>
using namespace std;
struct Date
{
int year;
int month;
int day;
};
bool is_leap(int);
int days_month(Date*,int);
int main()
{
int days = 0;
//define two structure to store two date;
Date date1;
Date date2;
//enter the first date;
cout << "Please enter the first date : ";
cin >> date1.year >> date1.month >> date1.day;
//enter the second date;
cout << "Please enter the next date : ";
cin >> date2.year >> date2.month >> date2.day;
//Lock the date;
Date *front = &date1,*back = &date2;
if(date1.year > date2.year)
{
front = &date2;
back = &date1;
}
else if(date1.year == date2.year && date1.month > date2.month)
{
front = &date2;
back = &date1;
}
else if(date1.year == date2.year && date1.month == date2.month && date1.month > date2.month)
{
front = &date2;
back = &date1;
}
//caculate the days;
if(front->year != back->year)
{
//the situation that years are different
//the days of the front date left in its year;
int right = 0;
for(int i = front->month + 1;i <= 12;i++)
{
right += days_month(front,i);
}
right += (days_month(front,front->month) - front->day);
//the days of the back date behind the day;
int left = 0;
for(int i = 1;i < back->month;i++)
{
left += days_month(back,i);
}
left += back->day;
//the days between two years;
int days_year = 0;
for(int i = front->year;i < back->year - 1;i++)
{
if(is_leap(i))
{
days_year += 366;
}else
{
days_year += 365;
}
}
days = right + left + days_year;
}else if(front->month != back->month)
{
//the situation that two date in the same year but month
days = days_month(front,front->month) - front->day;
for(int i = front->month + 1;i < back->month;i++)
{
days += days_month(front,i);
}
days += back->day;
}else
{
//the situation that two date only different from day
days = back->day - front->day;
}
//print the result
cout << "The days between two date is "
<< days << endl;
}
bool is_leap(int y)
{
bool r;
if((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
{
r = true;
}else
{
r = false;
}
return r;
}
int days_month(Date* date,int i)
{
int feb,r;
//set the days of February
if(is_leap(date->year))
{
feb = 29;
}else
{
feb = 28;
}
switch (i)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
r = 31;break;
case 4:
case 6:
case 9:
case 11:
r = 30;break;
case 2:
r = feb;
}
return r;
}
运行结果