星期几问题

参考九度OJ 1043
题目描述:
We now use the Gregorian style of dating in Russia. The leap years are years with number divisible by 4 but not divisible by 100, or divisible by 400.
For example, years 2004, 2180 and 2400 are leap. Years 2004, 2181 and 2300 are not leap.
Your task is to write a program which will compute the day of week corresponding to a given date in the nearest past or in the future using today’s agreement about dating.
输入:
There is one single line contains the day number d, month name M and year number y(1000≤y≤3000). The month name is the corresponding English name starting from the capital letter.
输出:
Output a single line with the English name of the day of week corresponding to the date, starting from the capital letter. All other letters must be in lower case.
样例输入:
9 October 2001
14 October 2001
样例输出:
Tuesday
Sunday

这题用蔡勒公式WA了,可能是我算错了。后来直接改为计算与公元1年1月1日相差的天数,然后%7就OK~~(起初我以为公元从0年1月1日开始,捂脸!!)

/* Name:DayOfWeek.cpp Author:LinXiaoBai CreateOn:2016/03/07 Function:给定日期计算星期。与公元1年1月1日相差的天数%7 */
# include<iostream>
# include<string>
using namespace std;
int main()
{
    int day,year;
    string month;
    int m[13]= {0,31,28,31,30,31,30,31,31,30,31,30,31};
    string strm[13]= {"","January","February","March","April","May","June","July","August","September","October","November","December"};
    string  week[7]= {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
    while(cin>>day>>month>>year)
    {
        int cn=0,sumd=0;
        for(int i=1; i<year; i++) //公元1年到该年之间有多少个闰年
            if((!(i%4)&&(i%100))||!(i%400))
                cn+=1;
        sumd+=365*(year-1)+cn;
        int i;
        for(i=1; i<=12; i++) //字符串格式的月份转成数字
            if(!strm[i].compare(month))
                break;
        for(int j=1; j<i; j++)  //加上此月之前的天数
            sumd+=m[j];
        if(i>2&&((!(year%4)&&(year%100))||!(year%400))) //如果是闰年多加一天
            sumd++;
        sumd+=day;
        int w=sumd%7;
        cout<<week[w]<<endl;
    }
    return 0;
}

你可能感兴趣的:(算法,星期几问题)