打印月历(C语言)

打印月历

  • 需要考虑的问题不多,第一,判断此年是不是闰年。
  • 判断判断此年的12个月份中每一天的天数。
  • 还需要知道这个月的第一天是星期几。
  • 为此,我们定义一个基准年。就是告诉用户这年的第一天开始时间,然后在来计算别的月份。
代码程序比较简单,我直接放代码了
#include <stdio.h>
#include <stdlib.h>

int months[2][13] = {
    { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },    //非闰年的12个月
    { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }     //闰年的12个月
};

int isLeap(int year)    //判断是否为闰年
{
    return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
}

int first_day_of_year(int year)  //首先定义一个基准年
{
    int base_year = 2000;
    int base_first_day = 6;
    int total = 0;
    for (int i = base_year; i<year; i++) {
        total += 365 + isLeap(i);
    }

    return (total + base_first_day) % 7;
}

int first_day_of_month(int year, int month, int first_year)    用户输入的年份
{
    int total = 0;

    for (int i = 1; i<month; i++) {
        total += months[isLeap(year)][i];
    }
    total += first_year;

    return total % 7;
}

void show(int year, int month, int first)
{
    printf("Sun Mon Tue Wed The Fri Sat\n");
    printf("---------------------------\n");
    for (int i = 0; i<first; i++)
        printf("    ");
    for (int i = 1; i <= months[isLeap(year)][month]; i++) {
        printf("%3d ", i);
        if ((i + first) % 7 == 0)
            printf("\n");
    }
}

int main(int argc, char *argv[])
{
    int year, month;
    printf("year/month: ");
    scanf_s("%d/%d", &year, &month);

    int first_year = first_day_of_year(year);
    int first_month = first_day_of_month(year, month, first_year);
    show(year, month, first_month);
    system("pause");
    return 0;
}
程序较简单,有不懂的欢迎留言,如有错误,还请大神指点。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值