按固定格式输入一个日期:比如2012-02-02,输出他是本年的第几天,周几

这是一个很常见的问题,因同学问我该怎样实现。今天闲来无事,就实现了一下。算法很简单,很适合作为C/C++的基础训练题。


//判断是不是闰年
bool IsLeapYear(int nYear)
{
	if(nYear <= 0)
		exit(0);
	if((nYear%4 == 0 && nYear%100 != 0) || (nYear%400 == 0))
		return true;
	else 
		return false;
}

//检查输入的日期是否合法
bool CheckDate(int nYear,int nMonth,int nDay)
{
	if(nYear <0 || nMonth<0 || nDay<0)
		exit(0);
	int nLeapYearMonth[] = {31,29,31,30,31,30,31,31,30,31,30,31}; //闰年对应月份的天数
	int nNoLeapYearMonth[] = {31,28,31,30,31,30,31,31,30,31,30,31}; //非闰年对应月份的天数
	if(IsLeapYear(nYear))
	{
		if(nDay <= nLeapYearMonth[nMonth-1])
			return true;
		else 
			return false;
	}
	else
	{
		if(nDay <= nNoLeapYearMonth[nMonth-1])
			return true;
		else 
			return false;
	}
	return false;
}

int DayOfYear(string &strDate)
{
	if(strDate.c_str() == NULL)
		exit(0);
	int nLeapYearMonth[] = {31,29,31,30,31,30,31,31,30,31,30,31}; //闰年对应月份的天数
	int nNoLeapYearMonth[] = {31,28,31,30,31,30,31,31,30,31,30,31}; //非闰年对应月份的天数

	//把传入固定格式的日期分解
	string strTemp = strDate;
	int nStart,nPos;
	string strYear,strMonth,strDay;
	nStart = 0;
	nPos = strTemp.find('-',nStart);
	strYear.assign(strTemp,nStart,nPos);
	nStart = nPos+1;
	nPos = strTemp.find('-',nStart);
	strMonth.assign(strTemp,nStart,2);
	nStart = nPos+1;
	strDay.assign(strTemp,nStart,2);
	int nYear = atoi(strYear.c_str());
	int nMonth = atoi(strMonth.c_str());
	int nDay = atoi(strDay.c_str());

	if(!CheckDate(nYear,nMonth,nDay))
		exit(0);

	//计算这是今年的第几天
	int nDayOfYear = 0;
	int nIndex = 0;
	if(IsLeapYear(nYear))
	{
		nIndex = nMonth-2;
		while(nIndex >= 0)
		{
			nDayOfYear += nLeapYearMonth[nIndex];
			nIndex--;
		}
		nDayOfYear += nDay;
	}
	else
	{
		nIndex = nMonth-2;
		while(nIndex-- >= 0)
		{
			nDayOfYear += nNoLeapYearMonth[nIndex];
			nIndex--;
		}
		nDayOfYear += nDay;
	}
	return nDayOfYear;
}

关于计算这一天是星期几,我的想法是从世界上的第一个星期一算起到今天有多少天,然后模7求余数。余数是几就是星期几。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值