日期判断是一个非常常见的题目类型,日期合法判断也是一个经典多参数函数的例题。
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;
}