输入年月日 判断输入十否合法在输出是这年第几天的问题。
RT 关键是看判断输入的日期是否合法的子函数。 代码如下:#include <stdio.h>int main(void)
{
int sum_day(int, int);
int leap(int year);
int exclude(int, int, int);
int year, month, day, days;
printf("Input date(year, month, day):");
scanf("%d,%d,%d", &year, &month, &day);
printf("%d/%d/%d", year, month, day);
if (exclude(year, month, day))
{
days = sum_day(month, day);
if (leap(year) && month >= 3)
days = days + 1;
printf("is the %dth day in the year.\n", days);
}
else
printf("\nData error! Please enter again:\n") && main();
return 0;
}
int sum_day(int month, int day)
{
int day_tab[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} ;
int i;
for (i = 1; i < month; i++)
day += day_tab[i];
return(day);
}
int leap(int year)
{
int leap;
leap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0 ;
return(leap);
}
int exclude(int year, int month, int day)
{
if ( (month <= 0 || month > 12 ) || (day <= 0 || day > 31))
return (0);
else
{
if (leap(year))
{
switch (month)
{
case 4:
case 6:
case 9:
case 11: if (day == 31) return (0); break;
case 2: if (day > 29) return (0); break;
default : return (1); break;
}
}
else
if (!leap(year))
{
switch (month)
{
case 4:
case 6:
case 9:
case 11: if (day == 31) return (0); break;
case 2: if (day > 28) return (0); break;
default : return (1); break;
}
}
}
}
经过 exclude()子函数除2月份所有的不合法日期都能排除, 但是2月份无论是第几天都不合法。为什么?
[ 本帖最后由 有容就大 于 2011-12-16 22:51 编辑 ]