版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mx_windxiao/article/details/52883605
以前听过的一道题目,设公元1年1月1日是星期一,考虑闰年的情况,随意输入年月日,返回星期几。
刚拿到题目觉得挺简单,返回星期,刚开始想直接在输入的那一年里计算,不用算其它年份,来返回星期,然后试了一下总是不能确定那一年的星期,因为要考虑闰年,以前的年份中的闰年数量返回后还要考虑用户输入年份是否是闰年,是闰年的话日期在2月29号前还是后,考虑的东西太多,容易出错,然后就换一个思路想,,因为闰年的缘故每年的天数都是会变得,每月的天数也是会变得,那不变的就剩下星期了,一周七天是不会变的,既然公元1年1月1日是星期一,那直接算出公元1年1月1日到用户输入的日期一共多少天和7取余就可以了,代码如下:
#include <iostream>
using namespace std;
int main()
{
int year, mouth, day, week, Ycount = 0, Mcount = 0;
int DYear, MDay, AllDay;
cout << "请输入年:";
cin >> year;
cout << "请输入月:";
cin >> mouth;
cout << "请输入日:";
cin >> day;
if (year > 1)
{
for (int i = 1; i < year; i++)
{
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0)
Ycount++;
}
DYear = year * 365 + Ycount;
}
else
DYear = 0;
int Mouth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
for (int i = 0; i < mouth-1; i++)
{
Mcount += Mouth[i];
}
AllDay = DYear + Mcount + day;
cout << AllDay << endl;
week = AllDay % 7;
if(week==0)
cout << year << "年" << mouth << "月" << day << "日是星期日" << endl;
else
cout << year << "年" << mouth << "月" << day << "日是星期" << week << endl;
}
def week(year, mouth, day):
Ycount = 0
if year > 1:
for i in range(1, year):
if i % 4 ==0 and i % 100 != 0 or i % 400 == 0:
Ycount += 1
Dyear = year * 365 + Ycount
else:
Dyear = 0
Mouth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
Mcount = 0
for i in range(mouth-1):
Mcount += Mouth[i]
AllDay = Dyear + Mcount + day
week = AllDay % 7
if week == 0:
print('%d年%d月%d日是星期日' % (year,mouth,day))
else:
print('%d年%d月%d日是星期%d' % (year, mouth, day, week))
def main():
while True:
year = int(input('请输入年:'))
mouth = int(input('请输入月:'))
day = int(input('请输入日:'))
week(year, mouth, day)
if __name__ == '__main__':
main()