编程序,输入年份和月份,输出本月有多少天。合理选择分支语句完成设计任务。

本文提供两种使用C语言编写的程序,用于判断输入的年份和月份对应的天数,考虑了平年和闰年2月的特殊情况。第一种代码采用switch-case结构,第二种代码通过if-else语句实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题及代码:

样例输入1:2004 2
输出结果1:本月29天
样例输入2:2010 4
输出结果2:本月30天

代码:

1、代码1:

#include <stdio.h>
#include <math.h>

int main()
{
    int y,m;
    scanf("%d %d",&y,&m);
    switch(m)
    {
    case 1:
    case 3:
    case 5:
    case 7:
    case 8:
    case 10:
    case 12:
        printf("本月31天");
        break;
    case 4:
    case 6:
    case 9:
    case 11:
        printf("本月30天");
        break;
    case 2:
    {
        if(y%4==0&&y%100!=0||y%400==0)
        {
            printf("本月有29天");
        }
        else
        {
            printf("本月有28天");
        }
    }
    }
    return 0;
}

2、代码2:

#include <stdio.h>
int main ( )
{
    int  year, month, days;
    printf("请输入年、月: ");
    scanf("%d %d", &year, &month);
    if(month==2)
    {
        if((year%4==0  &&  year%100!=0)||(year%400==0))
            days=29;
        else
            days=28;
    }
    else
    {
        if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)
            days=31;
        else
        {
            if(month==4 || month==6 || month==9 || month==11)
                days=30;
        }
    }
    printf("%d 年 %d 月共有 %d 天。\n", year, month, days);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值