1. 程式人生 > >程式練習2016.10.21

程式練習2016.10.21

        以前聽過的一道題目,設公元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;
}


以下為Python實現:

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()