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

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

注意方法二中sscanf的用法

方法一:

#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;
}

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页