用函数判断日期是否合法C语言实现

日期判断是一个非常常见的题目类型,日期合法判断也是一个经典多参数函数的例题。

Description

编写函数,判断一个日期(年-月-日)是否合法;如果合法,则返回1;如果月份不合法,
则返回-1;如果日子不合法,则返回-2。程序中判断年份是否为闰年的功能也用函数实现。(主函数代码部分已经写好,只需写函数部分,如果提交的不是c语言则需要提交全部代码)

Output

判断这个日期(年-月-日)是否合法;如果合法,则返回1;如果月份不合法,则返回-1;如果月份合法且日子不合法,则返回-2,月份和日子都不合法,则返回-1。(年份算作永远合法)

 #include<stdio.h>

#include<math.h>

int happy(int year, int month, int day);

int main() {

        char ch;

        int year, month, day;

while (scanf("%d%c%d%c%d", &year, &ch, &month, &ch, &day) != EOF) {

printf("%d ", happy(year, month, day));

}

return 0;

} 

以上为题目描述。
日期判断合法主要取决于闰年闰月的判断是否正确,下面是我编写的代码。

int happy(int year, int month, int day)
{
    if (month > 12 || month < 1)
    {
        return -1;
    }
    else
    {
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)//是闰年
        {
            if (month == 2)
            {
                if (day > 29 || day < 1)
                    return -2;
                else
                    return 1;
            }
        }
        if (month == 4 || month == 6 || month == 9 || month == 11)
        {
            if (day < 1 || day>30)
                return -2;
            else return 1;
        }
        else if (month != 2)
        {
            if (day < 1 || day>31)
                return -2;
            else
                return 1;
        }
        else
        {
            if (day < 1 || day>28)
                return -2;
            else
                return 1;
        }
    }
    return 1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值