switch作业练习

42 阅读1分钟

题目:输入月份,输出当月天数

要求:1-->31 2-->继续询问用户,请输入年份,根据是否闰年判断,输出28,29 3-->31 4-->30

#include<stdio.h>
#include <stdlib.h>
int main(){
	//输入月份,输出当月天数
	// 1-->31
	//2-->继续询问用户,请输入年份,根据是否闰年判断,输出28,29
	//3-->31
	//4-->30
    int month, year, days;

    printf("请输入月份(1-12):");
    scanf("%d", &month);

    switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            days = 31;
            break;

        case 4:
        case 6:
        case 9:
        case 11:
            days = 30;
            break;

        case 2:
            printf("请输入年份:");
            scanf("%d", &year);

            if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
                days = 29;
            } else {
                days = 28;
            }
            break;

        default:
            printf("输入的月份无效!\n");
            return 1; 
    }

    printf("%d月有%d天\n", month, days);
    return 0;
}

演示如下:

image.png

image.png