北理08计算机复试上机——处理日期(两日期间隔、日期相加)

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

int daytab[2][12] = {
		{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},//平年 
		{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}//闰年 
	};
bool isrun(int year){//判断是否为闰年 
	return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
}
int count(int year, int month, int day){//计算当前日期是今年第几天 
	int ans = 0, i;
	if(isrun(year)){//闰年 
		for(i = 0; i < month - 1; ++i){
			ans += daytab[1][i];
		}
		ans += day;
	}else{
		for(i = 0; i < month - 1; ++i){
			ans += daytab[0][i];
		}
		ans += day;
	}
	return ans;
}	

void cal(int year, int month, int day, int len){
	int total, i;
	total = count(year, month, day);
	total += len;
	while(1){//处理年份 
		if(isrun(year) && total > 366){
			++year;
			total -= 366;
		}else if(!isrun(year) && total > 365){
			++year;
			total -= 365;
		}else{
			break;
		}
	}
	month = 1;
	if(isrun(year)){
		for(i = 0; i < 12; ++i){//处理月份 
			if(total > daytab[1][i]){
				total -= daytab[1][i];
				++month;
			}else{
				break;
			}
		}
	}else{
		for(i = 0; i < 12; ++i){//处理月份 
			if(total > daytab[0][i]){
				total -= daytab[0][i];
				++month;
			}else{
				break;
			}
		}
	}
	day = total;//处理日期
	cout<<"处理后日期为:"<<year<<"-"<<month<<"-"<<day<<endl; 
}
	
int main(int argc, char *argv[]) {
	int func;
	cout<<"命令1后输入两行,表示两个日期(yyyy-mm-dd),计算两个日期间隔"<<endl;
	cout<<"命令2后输入两行,第一行为日期,第二行为间隔天数"<<endl;
	cin>>func;
	int year1, month1, day1, year2, month2, day2, len;
	if(func == 1){
		scanf("%d-%d-%d", &year1, &month1, &day1);
		scanf("%d-%d-%d", &year2, &month2, &day2);
		printf("两日期相隔%d天\n", count(year2, month2, day2) - count(year1, month1, day1));
	}else if(func == 2){
		scanf("%d-%d-%d", &year1, &month1, &day1);
		scanf("%d", &len);
		cal(year1, month1, day1, len);
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值