# 考研机试真题 日期差值 模拟

## 方法一：

#include<cstdio>
#include<cmath>
#include<iostream>
using namespace std;
char a[8];
char b[8];
int c[2][13] = { {0,31,28,31,30,31,30,31,31,30,31,30,31},{0,31,29,31,30,31,30,31,31,30,31,30,31} };

bool isRyear(int year)
{
if ((!(year % 400)) || (year % 100 && !(year % 4)))
return 1;
else return 0;
}
int count(int year, int month, int day)
{
int x = isRyear(year);
int cnt = 0;
for (int i = 1; i <= month; i++)
{
if (i < month)
cnt += c[x][i];
else cnt += day;
}
return cnt;
}

int main()
{
while (scanf("%s%s", a, b) != EOF)
{
int altol = 0;
int year1, month1, day1;
int year2, month2, day2;

day1 = a[7] - '0' + (a[6] - '0') * 10;
day2 = b[7] - '0' + (b[6] - '0') * 10;
month1 = a[5] - '0' + (a[4] - '0') * 10;
month2 = b[5] - '0' + (b[4] - '0') * 10;
year1 = 0;
year2 = 0;
int cc = 1;
for (int i = 3; i >=0; i--)
{
year1 += (a[i] - '0')*cc;
year2 += (b[i] - '0')*cc;
cc *= 10;
}

int new_year1 = year1 > year2 ? year2 : year1;
int new_year2 = year1 > year2 ? year1 : year2;
for (int i = new_year1; i <= new_year2; i++)
{
if (new_year1 == new_year2)
altol += abs(count(new_year2, month2, day2) - count(new_year1, month1, day1));
else if (i == new_year1)
{
if (isRyear(i))
altol += (366 - count(new_year1, month1, day1));
else altol += (365 - count(new_year1, month1, day1));
}
else if (i == new_year2)
{
altol += count(new_year2, month2, day2);

}
else if (isRyear(i))
altol += 366;
else altol += 365;

}
printf("%d\n", ++altol);

}
return 0;
}



## 方法二：

#include<iostream>
using namespace std;
int daytab[2][13]={
{0,31,28,31,30,31,30,31,31,30,31,30,31},
{0,31,29,31,30,31,30,31,31,30,31,30,31}
};
bool isLeapYear(int year){
if(year%100!=0&&year%4==0||year%400==0)
return true;
return false;
}
char a[9],b[9];
int main(){
//n为第一个日期相对于0000 00 00的差值，n1为为第二个的差值
int year,month,day,year1,month1,day1,n,n1;
while(cin>>a>>b){
n=n1=0;
sscanf(a,"%4d%2d%2d",&year,&month,&day);//格式化读入
sscanf(b,"%4d%2d%2d",&year1,&month1,&day1);
for(int i=0;i<=year;i++){//记录年差值
if(isLeapYear(i)){
n+=366;
}else n+=365;
}for(int i=1;i<month;i++){//记录月差值
n+=daytab[isLeapYear(year)][i];
}n+=day;//记录日差值
for(int i=0;i<=year1;i++){
if(isLeapYear(i)){
n1+=366;
}else n1+=365;
}for(int i=1;i<month1;i++){
n1+=daytab[isLeapYear(year1)][i];
}n1+=day1;
cout<<abs(n-n1)+1<<endl;//差值相减取绝对值+1即可
}
return 0;
}


• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

诠释你的Mr贾

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

01-28
03-11

04-18
04-13 8168
12-12 2752
02-27 1044
03-04 4744
04-01 3315
05-01 1355
06-20 3882
06-29 662
03-25 2367
03-21 5785
02-29 2163
10-05 6827
02-14 8751
09-21 1874
02-26 2064