编程珠玑课后题答案3.4

问题描述:给出两个日期计算两者的天数距离;给出一个日期确定之周几;打印出给出年月的日历

参考:

http://blog.csdn.net/johnnyhu90/article/details/43052601



#include <iostream>
#include <cassert>
using namespace std;
//有效月份1-12
const int DAYS_EVERYMONTH[13] = {0,31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
typedef struct
{
	int year;
	int month;
	int day;
}date;

int which_days(date d)//该日期是本年的那一天
{
	int sum_day=0;
	int month_2=28;
	if(d.year % 400 == 0 || ( d.year % 100 != 0 && d.year % 4 == 0) && d.month>2)
		sum_day+=1;
	for(int i=1;i<d.month;i++)
	{
		sum_day+=DAYS_EVERYMONTH[i];
	}
	sum_day+=d.day;

	return sum_day;
}
int cmp(date d1,date d2)//是否d2的日期更靠后
{
	if(d1.year==d2.year)
		if(d1.month==d2.month) 
			return d1.day<d2.day;
		else
			return d1.month<d2.month;

	return d1.year<d2.year;
}
int cal_day(date d1,date d2)
{
	int flag=1;
	if(!cmp(d1,d2))//为了防止在计算过程中出现日期为负的,所以需要处理
	{
		date temp=d1;
		d1=d2;
		d2=temp;
		flag=-1;
	}
	int res_day=0;
	if(d1.year==d2.year)
		return (which_days(d2)-which_days(d1))*flag;
	for(int i=d1.year;i<d2.year;i++)
	{
		if( i % 400 == 0 || ( i % 100 != 0 && i % 4 == 0))
			res_day+=366;
		else
			res_day+=365;
	}
	res_day+=which_days(d2)-which_days(d1);
	return res_day*flag;
}

int get_day_of_week(date d)
{
	const date coordinate={2017,7,24};
	int Week=1;
	int days=cal_day(coordinate,d);
	int week=(days+Week)%7;//以周日(0)开始计算
	return week>=0? week:(7-abs(week));
}

void Print_calendar(date d)
{
	int month_days=0;
	if(d.month==2)
		if(d.year%400==0 || (d.year%100!=0&&d.year%4==0))
			month_days=29;
		else
			month_days=28;
	else
		month_days=DAYS_EVERYMONTH[d.month];

	printf("%d-%d日历\n",d.year,d.month);
	printf("Sun\tMon\tTues\tWed\tThur\tFri\tSat\n");
	d.day=1;
	int week=get_day_of_week(d);//本月1号周几
	int i=0;
	for(i=0;i<week;i++)
		printf("\t");
	int day=1;
	while(day<=month_days)
	{
		printf("%d",day++);
		i++;
		if(i%7==0)
			printf("\n");
		else
			printf("\t");
	}
	printf("\n");
}

int main()
{	
	date d1={2011,3,20};
	date d2={2017,7,24};
	
	cout<<"两个日期的间隔:"<<cal_day(d1,d2)<<endl;
	date d3={2016,7,23};//
	cout<<"2017-7-21是星期 "<<get_day_of_week(d3)<<endl;
	Print_calendar(d2);
	system("pause");

    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值