复旦大学计算机学院上机考试——(2019-1) 相隔天数

题目描述:

输入日期格式:YYYYMMDD,求与20190205相隔天数。

样例输入:

输入:

20190208

输出:

3

思路:

这道题短小精悍,还是有点难度的。

用数组a[13][2]记录每月的天数,其中a[1][0]表示不是闰年时1月的天数, a[1][1]表示闰年时1月的天数。

然后根据数组中的数据作为进位的边界。

闰年:

闰年是公历中的名词。闰年分为普通闰年和世纪闰年。

普通闰年:公历年份是4的倍数的,且不是100的倍数,为普通闰年。(如2004年就是闰年);

世纪闰年:公历年份是整百数的,必须是400的倍数才是世纪闰年(如1900年不是世纪闰年,2000年是世纪闰年);

代码:

1.一开始的写法,很臭很长。

#include <cstdio>
#include <algorithm>
using namespace std;

int a[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}}; 

int isLeap(int year){
	if(year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) return 1;
	else return 0;
}

int main(){
	int time1 ;
	scanf("%d", &time1);

	int y1 = time1 / 10000;
	int m1 = time1 % 10000 / 100;
	int d1 = time1 % 100;
	
	
	int count = 0;
	
	while(y1 != 2019 || m1 != 2 || d1 != 5){
		if(y1 == 2019){
			if(m1 > 2){
				if(d1 > 1){
					d1--;
					count++;
				}else{
					m1--;
					d1 = a[m1][isLeap(y1)];
					count++;
				}
			}else if(m1 < 2){
				if(d1 < a[m1][isLeap(y1)]){
					d1++;
					count++;
				}else{
					m1++;
					d1 = 1;
					count++;
				}
			}else{
				if(d1 < 5){
					d1++;
					count++;
				}else if(d1 > 5){
					d1--;
					count++;
				}else break;
			}
		}else if(y1 < 2019){
			if(d1 < a[m1][isLeap(y1)]){
				d1++;
				count++;
			}else{
				if(m1 < 12){
					d1 = 1;
					m1++;
					count++;
				}else{
					y1++;
					m1=1;
					d1=1;
					count++;
				}
			}
		}else{
			if(d1 > 1){
				d1--;
				count++; 
			}else{
				if(m1 > 1){
					m1--;
					d1 = a[m1][isLeap(y1)];
					count++;
				}else{
					y1--;
					m1 = 12;
					d1 = a[m1][isLeap(y1)];
					count++;
				}
			}
		
		}
	}
	
	
	
	printf("%d", count);
	return 0;
}

2.改进后
 

#include <cstdio>
#include <algorithm>
using namespace std;

int a[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}}; 

int isLeap(int year){
	if(year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) return 1;
	else return 0;
}

int main(){
	int time1 ;
	int time2 = 20190205;
	scanf("%d", &time1);
	if(time1 > time2) swap(time1, time2);
	int y1 = time1 / 10000;
	int m1 = time1 % 10000 / 100;
	int d1 = time1 % 100;
	
	int y2 = time2 / 10000;
	int m2 = time2 % 10000 / 100;
	int d2 = time2 % 100;
	
	int count = 0;
	
	while(y1 < y2 || m1 < m2 || d1 < d2){
		if(d1 < a[m1][isLeap(y1)]){
			d1++;
			count++;
		}else{
			if(m1 < 12){
				m1++;
				d1 = 1;
				count++;
			}else{
				y1++; 
				d1 = 1;
				m1 = 1;
				count++;
			}
		}
	}
	
	
	
	printf("%d", count);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值