题目链接
题目大意:
输入一个日期,要求输出该日期为星期几。
解题思路:
先确定原点日期,然后我们只需要求出所给的日期与今天的日期相隔了几天,将差值对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;
}
本文介绍了一种将任意日期转换为星期几的算法实现。通过确定原点日期,计算目标日期与原点日期之间的天数差,利用此差值与当前星期几结合,即可准确得到目标日期对应的星期。代码中详细展示了如何处理平年与闰年的月份天数,以及如何通过模运算确定星期。
518

被折叠的 条评论
为什么被折叠?



