C语言简易万年历带注释

同学问的课后作业,顺便加了写注释。

#include<stdio.h>

/*
 * 注意 每周的第一天是星期天
 */

int main() {
    int day_per_mo[12] = {
            31, 28, 31, 30, 31, 30,
            31, 31, 30, 31, 30, 31
    };  // 12个月的天数
    int fir_weekday[12]; // 12个月的第一天是星期几

    int i, year = 0, month;

    printf("输入年份:");

    scanf("%d", &year);

    if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) { // 判断是否为闰年
        day_per_mo[1] = 29;
    }

    fir_weekday[0] =
            (int) (year - 1 + (year - 1) / 4.0 - (year - 1) / 100.0 + (year - 1) / 400.0 + 1) % 7; // 计算该年第一天是星期几
    // 365 % 7 = 1
    // 366 % 7 = 2
    // 距离公元元年的天数 + 闰年数 同余 当年第一天是星期几 mod 7

    for (i = 1; i < 12; i++) {
        fir_weekday[i] = (day_per_mo[i - 1] + fir_weekday[i - 1]) % 7;// 计算每个月的第一天是星期几
    }
    int opt = 0;
    while (1) {
        printf("请输入月份:");
        scanf("%d", &opt);
        if (opt < 0 || opt > 12) {
            printf("输入错误");
            continue;
        }
        break;
    }

    for (month = 0; month < 12; month++) {
        if (opt != 0 && opt != month + 1) continue;
        printf("\n %d月\n", month + 1);  // 输出月份
        printf("\n 日 一 二 三 四 五 六\n"); // 输出星期表头

        for (i = 0; i < fir_weekday[month] * 3; i++)
            printf(" "); // 输出第一天前的空格,占用位

        for (i = 1; i <= day_per_mo[month]; i++) {
            printf("%3d", i); // 输出日期

            if ((i + fir_weekday[month]) % 7 == 0)
                printf("\n"); // 到周六换行
        }
        printf("\n");

    }
    return 0;
}
posted @ 2024-02-01 00:58  Icys  阅读(10)  评论(0编辑  收藏  举报