Day of Week 九度教程第7題 求某一天是周幾

題目鏈接
題目大意:
輸入一個日期,要求輸出該日期爲星期幾。

解題思路:
先確定原點日期,然後我們只需要求出所給的日期與今天的日期相隔了幾天,將差值對7求餘數,再根據今天是星期幾,便能得出答案。
AC代碼:

#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>
using namespace std;
#define isyeap(x) (x % 100 !=0 && x % 4 == 0 ) || x % 400 == 0  ? 1 : 0
struct date {
	int year;
	string month;
	int day;
};
int daysofmonth[2][13] = { { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
{ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } };
string month[12] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
string week[7] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
int count(date a) {
	int mycount = 0;
	for (int i = 0; i < a.year; i++) {
		if (isyeap(i)) mycount += 366;
		else mycount += 365;
	}
	int thismonth;
	for (int i = 0; i < 12; i++) {
		if (month[i] == a.month) {
			thismonth = i + 1 ;
			break;
		}
	}
	for (int i = 0; i < thismonth; i++) {
		if (isyeap(a.year)) {
			mycount += daysofmonth[0][i];
		}
		else mycount += daysofmonth[1][i];
	}
	mycount += a.day;
	return mycount;
}
int main() {
	date today;
	today.year = 2019;
	today.month = "September";
	today.day = 2;
	int todayofweek = 1;
	int num2 = count(today);
	date a;
	while (cin>>a.day>>a.month>>a.year) {
		int num1 = count(a);
		int num3 = (num1 - num2);
		int t = ((num3 % 7) + 7) % 7;
		cout << week[t] << endl;
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章