zoukankan      html  css  js  c++  java
  • 日历

    这是老师给我们布置的一个实验课做的,用于理解大化小,模块化实现。但因为一些原因,就让我们自行解决了,我记得当时学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);
    }

    注释又没有打,不过我把每个函数实现的功能说清楚了,如果读者不了解函数功能是如何实现的话,可以留言!

  • 相关阅读:
    Median Value
    237. Delete Node in a Linked List
    206. Reverse Linked List
    160. Intersection of Two Linked Lists
    83. Remove Duplicates from Sorted List
    21. Merge Two Sorted Lists
    477. Total Hamming Distance
    421. Maximum XOR of Two Numbers in an Array
    397. Integer Replacement
    318. Maximum Product of Word Lengths
  • 原文地址:https://www.cnblogs.com/ranyang/p/13818047.html
Copyright © 2011-2022 走看看