注意:
①判断输入的年份、月份、天数要合法;
②其中天数不能超过该月的最大天数;
③区分平年和闰年。
代码如下:
int isLeapYear(int year)
{
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
{
return 0;//是闰年
}
else
{
return 1;//不是闰年
}
}
int days(int year, int month, int day)
{
int sum = 0;
int i = 0;
int Lmon[12] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; //闰年每月的天数
int Cmon[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; //平年每月的天数
switch (isLeapYear(year))//区分闰年和平年
{
case 0:
for (i = 0; i < month - 1; i++)
{
sum += Lmon[i];
}
break;
case 1:
for (i = 0; i < month - 1; i++)
{
sum += Cmon[i];
}
break;
default:
break;
}
if (0 == isLeapYear(year)) //判断该月的天数是否正确(第二步)
{
if (day > Lmon[month - 1])
{
return -1;
}
return sum + day;
}
else
{
if (day > Cmon[month - 1])
{
return -1;
}
return sum + day;
}
}
int main()
{
int year = 0;
int month = 0;
int day = 0;
int ret = 0;
printf("Please enter the date<****-**-**>: ");
scanf("%d-%d-%d", &year, &month, &day);
if (year > 0 && (month > 0 && month <= 12) && (day > 0 && day <= 31)) //判断输入日期是否合法(第一步)
{
ret = days(year, month, day);
if (ret != -1)
{
printf("%d-%d-%d is the %d day in this yeas.\n", year, month, day, ret);
}
else
{
printf("Error,this date does not exist!\n");
}
}
else
{
printf("Error,this date does not exist!\n");
}
system("pause");
return 0;
}
1.输入的年份不合法
2.输入的月份不合法
3.输入的天数不合法
4.正确测试