4、C++基础:日期类问题(2)

给定一个日期,求出该日为星期几(已知2002-3-28为星期四)

#include 
using namespace std;

#define ISYEAP(x) ((x%100!=0 && x%4==0) || x%400==0) ? 1 : 0

// 预存每月的天数,注意二月配合宏定义做特殊处理
int dayOfMonth[13][2] = {
  0,0,
  31,31,
  28,29,
  31,31,
  30,30,
  31,31,
  30,30,
  31,31,
  31,31,
  30,30,
  31,31,
  30,30,
  31,31
};

struct Date{
  int Day;
  int Month;
  int Year;
  void nextDay(){
    Day++;
    if(Day > dayOfMonth[Month][ISYEAP(Year)]){
      Day = 1;
      Month++;
      if(Month>12){
        Month = 1;
        Year++;
      }
    }
  }
};

int buf[3001][13][32]; // 保存预处理的天数
char monthName[13][20] = {
  "",
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
    "December"
}; // 月名

char weekName[7][20] = {
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday"
}; // 周名

int main(void){
  Date tmp;
    int cnt = 0;
    tmp.Day = 1;
    tmp.Month = 1;
    tmp.Year = 0;

    // 预处理出每一天与原点日期的天数差
    while(tmp.Year != 3001){
      buf[tmp.Year][tmp.Month][tmp.Day] = cnt;
      tmp.nextDay();
      cnt++;
    }

    cout << "输入年 月 日" << endl;
    cin >> tmp.Year >> tmp.Month >> tmp.Day;

    int days = buf[tmp.Year][tmp.Month][tmp.Day] - buf[2002][3][28]; // 已知2002-3-28为星期四

    cout << weekName[((days+4)%7+7)%7] << endl;

    return 0;

}

你可能感兴趣的:(4、C++基础:日期类问题(2))