1. 程式人生 > >程式設計珠璣課後題答案3.4

程式設計珠璣課後題答案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;
}