c语言万年历代码的题目及功能代码示例

题目:C语言实现万年历

功能:实现一个简单的万年历程序,能够根据用户输入的年份和月份,输出该月份的日历。

具体实现:

  1. 用户输入年份和月份。
  2. 根据输入的年份和月份,计算出该月的天数。
  3. 计算出该月的第一天是星期几,以确定日历的排版。
  4. 输出该月的日历,包括每一天的日期和星期几。

示例代码:

#include <stdio.h>

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

// 计算某年某月的天数
int getMonthDays(int year, int month) {
    int days = 0;
    switch (month) {
        case 2:
            days = isLeapYear(year) ? 29 : 28;
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            days = 30;
            break;
        default:
            days = 31;
            break;
    }
    return days;
}

// 计算某年某月第一天是星期几
int getFirstDayOfWeek(int year, int month) {
    int days = 0;
    int i;
    for (i = 1900; i < year; i++) {
        days += isLeapYear(i) ? 366 : 365;
    }
    for (i = 1; i < month; i++) {
        days += getMonthDays(year, i);
    }
    return (days + 1) % 7;
}

// 输出日历
void printCalendar(int year, int month) {
    int days = getMonthDays(year, month);
    int firstDayOfWeek = getFirstDayOfWeek(year, month);
    int i, j;
    printf("日 一 二 三 四 五 六\n");
    for (i = 0; i < firstDayOfWeek; i++) {
        printf("   ");
    }
    for (j = 1; j <= days; j++) {
        printf("%2d ", j);
        if ((j + firstDayOfWeek) % 7 == 0) {
            printf("\n");
        }
    }
    printf("\n");
}

int main() {
    int year, month;
    printf("请输入年份:");
    scanf("%d", &year);
    printf("请输入月份:");
    scanf("%d", &month);
    printf("%d年%d月的日历如下:\n", year, month);
    printCalendar(year, month);
    return 0;
}

运行示例:

请输入年份:2023
请输入月份:3
2023年3月的日历如下:
日 一 二 三 四 五 六
               1  2 
 3  4  5  6  7  8  9 
10 11 12 13 14 15 16 
17 18 19 20 21 22 23 
24 25 26 27 28 29 30

 
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:
确定