《C语言及程序设计》实践参考——本月有几天?

返回:贺老师课程教学链接  项目要求


【项目:本月有几天?】
编程序,输入年份和月份,输出本月有多少天。合理选择分支语句完成设计任务。
样例输入1:2004 2
输出结果1:本月29天
样例输入2:2010 4
输出结果2:本月30天


[参考解答]

#include <stdio.h>
int main ( )
{
    int  year, month, days;
    printf("请输入年、月: ");
    scanf("%d %d", &year, &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:
        if(year%4==0 && year%100!=0 ||year%400==0)
            days = 29;
        else
            days =28;
    }
    printf("%d 年 %d 月共有 %d 天。\n", year, month, days);
    return 0;
}

有同学写出的代码如下。其缺点之一在于将程序写得太长了,不够简洁,再者,即使输入的月分不是2月,也要判断是否闰年,是不是做了多余的事?
#include <stdio.h>
int main ( )
{
    int  year, month, days;
    printf("请输入年、月: ");
    scanf("%d %d", &year, &month);
    if(year%4==0 && year%100!=0 ||year%400==0)//闰年时的处理
    {
        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:
            days = 29;


        }
    }
    else   //非闰年
    {
        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:
            days =28;
        }
    }
    printf("%d 年 %d 月共有 %d 天。\n", year, month, days);
    return 0;
}

解法3:用if嵌套
#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;
}





  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迂者-贺利坚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值