11.6课堂作业

67 阅读1分钟

月份天数查询程序(含闰年判断)

编写一个C语言程序,实现“月份天数查询”功能。程序需要接收用户输入的月份(1-12),并根据月份规则输出该月对应的天数;当用户输入的月份为2月时,需要进一步询问用户输入年份,通过闰年判断逻辑.

代码:

#include <stdio.h>

int main(){
    // 输入月份,输出当月的天数
    int month, year;
    printf("请输入月份(1-12):");
    scanf("%d", &month);

    switch(month){
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            printf("该月有31天\n");
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            printf("该月有30天\n");
            break;
        case 2:
            // 判断闰年:能被4整除但不能被100整除,或能被400整除
            printf("请输入年份:");
            scanf("%d", &year);
            if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)){
                printf("该月有29天\n");
            } else {
                printf("该月有28天\n");
            }
            break;
        default:
            printf("输入的月份无效!\n");
            break;
    }
    return 0;
}

编译结果 image.png