`
hongbochen1223
  • 浏览: 44015 次
文章分类
社区版块
存档分类
最新评论

C实现万年历

 
阅读更多

要求:输入年份输出这一年的日历
注意:公元1900年一月一日是星期一,这一年是平年
思路:获取输入的年份y,首先获取从公元1900年到(y-1)年
的天数,然后获得该年份的第一天是星期几,进行输出。

这次实例,我花费了很长的时间,最后发现错误的原因出在在求某一年是闰年还是平年的时候,我没有田间return语句,也就是没有返回值,真是醉了。

我感觉这次我写代码的时候一点感觉都没有。哎,真是的,一颗老鼠屎,坏了一锅粥啊。

下面是我的代码:

#include <stdio.h>

//从1900年开始计算天数
#define BEGIN 1900

/**
 * 要求:输入年份输出这一年的日历
 * 注意:公元1900年一月一日是星期一,这一年是平年
 * 思路:获取输入的年份y,首先获取从公元1900年到(y-1)年
 * 的天数,然后获得该年份的第一天是星期几,进行输出。
 *
 * @brief main
 * @return
 */

int isRun(int year);

int main(void)
{
    //获取用户输入的年数
    int year;

    //存放从公元1年到year-1年的天数
    int days = 0;

    //用于保存星期几
    char **weeks[] = {"MON","TUE","WED","THU","FRI","SAT","SUN"};

    //二维数组,第一行用于存放闰年的月份
    //第二行用于存放平年的月份
    int runPing[2][12] = {
        {31,28,31,30,31,30,31,31,30,31,30,31},
        {31,29,31,30,31,30,31,31,30,31,30,31},
    };


    printf("Please enter the year:\n");

    scanf("%d",&year);

    int m;

    /** 计算从1900年到(year-1)的天数 **/
    for(m = BEGIN;m < year;m++){
        if(isRun(m)){
            days += 366;
        }else{
            days += 365;
        }
    }

    int which = 0;

    //判断year这一年是闰年还是平年
    if(isRun(year)){
        which = 1;
    }else{
        which = 0;
    }

    //进行输出
    for(m = 0;m < 12;m++){

        printf("MONTH:%d\n",m+1);

        //对7进行取余就能求得某一天是星期几
        int week = days % 7;

        if(week == 0){
            week = 7;  //如果余数是0,则为星期日
        }else{
            week += 1; //如果余数不是0,则余数+1,就是星期几
        }


        int i;

        //对上一个月的进行制表操作
        for(i = 0;i < 7;i++){
            printf("%s\t",weeks[i]);
        }

        printf("\n");

        for(i = 1;i<week;i++){
            printf("\t");
        }

        int n = 0;

        //输入某一个月的日期
        for(n = 0;n < runPing[which][m];n++){

            //在需要的时候进行换行操作
            if(n%7 == (7-week+1)){
                printf("\n");
            }

            printf("%d\t",n+1);
        }

        printf("\n\n");

        days += runPing[which][m];

    }



    return 0;
}

/**
 * @brief isRun 用于判断年year是否是闰年
 * @param year  被判断的那一年
 * @return
 *          0 - 表示是平年
 *          1 - 表示是闰年
 */
int isRun(int year){
    int run = 0;

    /**
     * 闰年的判断条件:
     * 1:能够被400整除
     * 2:能够被4整除,但是不能被100整除
     */
    if(((year%4==0)&&(year%100!=0)) || (year%400==0)){
        run = 1;
    }else{
        run = 0;
    }

    return run;
}

下面是我的程序的输出:

这里写图片描述

<script type="text/javascript"> $(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('<ul/>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('<li/>').text(i)); }; $numbering.fadeIn(1700); }); }); </script>

版权声明:本文为博主原创文章,未经博主允许不得转载。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics