这是一个很常见的问题,因同学问我该怎样实现。今天闲来无事,就实现了一下。算法很简单,很适合作为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求余数。余数是几就是星期几。