日曆
- 2020 年 10 月 14 日
- 筆記
這是老師給我們布置的一個實驗課做的,用於理解大化小,模組化實現。但因為一些原因,就讓我們自行解決了,我記得當時學c語言的時候,看到那一長串程式碼都腦袋疼,當時連照著抄輸出來的日曆都是千瘡百孔,出現了對不齊等一系列錯誤。
但是當我今天回頭看的時候,發現其實並沒有那麼難,每個函數實現了對應的功能,然後理解他是如何實現和處理得,理解後就按照他的思路把這個程式碼寫了出來。由於學的是c++,我就用了c++實現的。
#include <iostream>
#include <iomanip>
using namespace std;
#define Sunday 0
#define Monday 1
#define Tuesday 2
#define Wednesday 3
#define Thursday 4
#define Friday 5
#define Saturday 6
void GiveInstructions();//實現了給出提示的功能
int GetYear ();//讀取用戶想要輸出年份的日曆。
void PrintCalendar(int year);//輸出這一年的日曆。(按照12個月分開輸出)
void MonthOfYear(int month,int year);//輸出一年中每一個月對應的日曆。
int MonthDays(int month,int year);//返回這一個月對應得天數。
int FirstOfMonth(int month,int year);//返回每個月的第一天,用於判斷這個月的第一天是星期幾,便於輸出後面的。
int IsLeap (int year);//判斷是否是閏年,若是就返回1。
int main ()
{
GiveInstructions();
int year;
year = GetYear();
PrintCalendar(year);
return 0;
}
void GiveInstructions()
{
cout<<“You can enter the year which you want to know”<<endl
<<“The year must after 1900!”<<endl
<<“Please enter:”;
}
int GetYear ()
{
int year;
cin>>year;
return year;
}
void PrintCalendar(int year)
{
int i;
for(i = 1;i <= 12;i++) {
cout<<year<<“–“<<i<<endl;
MonthOfYear(i,year);
cout<<endl;
}
}
int MonthDays (int month,int year)
{
switch(month) {
case 2:
if(IsLeap(year)) return 29;
return 28;
case 4:case 6:case 9:case 11:
return 30;
default:
return 31;
}
}
int FirstOfMonth(int month,int year)
{
int weekday = Monday;
int i;
for(i = 1900;i < year;i++) {
weekday = (weekday + 365) % 7;
if(IsLeap(year)) weekday = (weekday + 1) % 7;
}
for(i = 1;i < month;i++) {
weekday = (weekday + MonthDays (i,year)) % 7;
}
return weekday;
}
void MonthOfYear(int month,int year)
{
int weekday,nDays,day;
nDays = MonthDays(month,year);
weekday = FirstOfMonth(month,year);
cout<<“Su Mo Tu We Tr Fr Sa”<<endl;
for(day = 1;day <= weekday;day++) {
cout<<” “;
}
for(day = 1; day <= nDays;day++) {
cout<<setw(2)<<day<<” “;
if (weekday == Saturday) cout<<endl;
weekday = (weekday + 1) % 7;
}
}
int IsLeap (int year)
{
return (((year % 4 == 0) && year % 100 != 0) || year % 400 == 0);
}
注釋又沒有打,不過我把每個函數實現的功能說清楚了,如果讀者不了解函數功能是如何實現的話,可以留言!